【问题标题】:react Push Object to array from list of arrarys从数组列表中将对象推送到数组
【发布时间】:2021-03-14 01:35:55
【问题描述】:

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

      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()
    ]

【问题讨论】:

  • 欢迎来到 SO! variants[index].sizes.push(newSize) --> push 的返回值只是一个数字,新的长度。我怀疑您是否想将长度存储在状态中。你的意思是concat 吗?另外,首先不要使用push 改变状态。

标签: arrays reactjs push use-state


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多