从数组列表中将对象推送到数组

react Push Object to array from list of arrarys

我正在尝试将对象推入数组列表中的特定数组。 我能够推送 ojbect,但它在 root 中创建了额外的数组。

      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() 创建一个带有颜色名称、id 和数组大小为空的对象 handleAddSize() 查找数组索引并将 ojbect 推送到 siezes

到目前为止,当我 运行 这段代码时,我能够做我想做的,但是当我点击 hadnleAddSize()

时,它是如何创建附加数组的
[
     {colorName : 'something', id: '234234', sizes : [{name: 'new', id:'2342']
    1 <-- this is created everytime I click on handleAddSize()
    ]

看来你想修改一个数组项,但是如果你使用push,你将修改原始数组(当你使用react state时你不应该这样做)而且push结果是一个数字表示数组的新长度,这就是为什么要向大小数组添加数字的原因。

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

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]);
};