首页 > 解决方案 > 从数组列表中将对象推送到数组

问题描述

我正在尝试将 ojbects 推送到数组列表中的特定数组中。我能够推送 ojbect,但它会在根目录中创建额外的数组。

      const [variants, setVariants] = useState([]);
    
      const colorNameRef = useRef('');
      const sizeNameRef = useRef('');
      const sizeSkuRef = useRef('');
    
      const addEntryClick = (e) => {
        e.preventDefault();
        const newEntry = {
          colorName: colorNameRef.current.value,
          id: e.timeStamp.toFixed(0),
          sizes: []
        };
        setVariants((preEntry) => [...preEntry, newEntry]);
     
      };
    
      const handleAddSize = (index) => (e) => {
        e.preventDefault();
        console.log(index);
     
        let newSize = {
          name: sizeNameRef.current.value,
          id: sizeSkuRef.current.value
        };          
    
        setVariants([...variants, variants[index].sizes.push(newSize)]);
     
      };
    
      function handleSubmit() {
        console.log(variants);
      }
return(
    <>
          <div>
            <input type="text" ref={colorNameRef} />
            <button onClick={addEntryClick}>Add</button>
          </div>
          <div>
            {variants &&
              variants.map((variant, index) => (
                <div key={index}>
                  <div className={variant.id}>{variant.id}</div>
                  <div>{variant.colorName}</div>
                  <div className="ftw=semi" data-id={variant.id}>
                    <div>
                      <input type="text" ref={sizeNameRef} />
                      <input type="text" ref={sizeSkuRef} />
                    </div>
    
                    <button className="btn-blue" onClick={handleAddSize(index)}>
                      Add
                    </button>
                  </div>
                  {/* {variant.sizes &&
                    variant.sizes.map((size, index) => (
                      <div key={index}>{size.name}</div>
                    ))} */}
                </div>
              ))}
          </div>
          <button onClick={handleSubmit}>Submit</button>
        </>
)

我正在寻找的理想结果是

[
 {colorName : 'something', id: '234234', sizes : [{}]
{colorName : 'something', id: '234234', sizes : [{}]
{colorName : 'something', id: '234234', sizes : [{}]
]

addEntryClick() 创建一个 ojbect,其中包含颜色名称、id 和空数组大小,handleAddSize() 查找数组索引并将 ojbect 推送到 siezes

到目前为止,当我运行此代码时,我能够完全按照我的意愿进行操作,但是当我单击 hadnleAddSize() 时,它会创建一些添加数组

[
     {colorName : 'something', id: '234234', sizes : [{name: 'new', id:'2342']
    1 <-- this is created everytime I click on handleAddSize()
    ]

标签: arraysreactjspushuse-state

解决方案


似乎您想修改一个数组项,但是如果您使用推送,您将修改原始数组(使用反应状态时不应该这样做),并且推送结果是一个指示数组新的数字长度,这就是为什么您要向大小数组添加一个数字。

如果你想修改数组而不改变它,有多种方法可以做到,这里是其中一种。

const handleAddSize = (index) => (e) => {
    e.preventDefault();
    console.log(index);

    const newSize = {
      name: sizeNameRef.current.value,
      id: sizeSkuRef.current.value
    };  

    // Returns a new modified array.
    const newModifiedArr = variants.map((item, currentIndex) => {
      // If the index matches with the current index
      if (currentIndex === index) {
        // Returns a new object with the sizes property modified to add your newSize object 
        return {
         ...item,
         sizes: [...item.sizes, newSize]
        }
      }
      // if the index does not match return the current item without modifying it.
      return item
    })        

    // Set the state with the new generated array
    setVariants([...newModifiedArr]);
};

推荐阅读