代码之家  ›  专栏  ›  技术社区  ›  Glory Raj

尝试使用react更新对象数组中的现有对象

  •  1
  • Glory Raj  · 技术社区  · 5 年前

     addedOpaqueMaterials = [{
                conductivity: 1
                density: 1
                id: "1"
                ......
                ......
             },
             {
                 conductivity: 2
                 density: 1
                 id: "2",
                 ......
                 ......
             }]
    

    从react状态我得到了对象的更新 id= 2 就像下面这样,

    {
        conductivity: 4
        density: 23
        id: "2",
        ......
        ......
    }
    

    我希望用这些值更新主数组中的对象,最好的更新方法是什么,下面是与此相关的代码。

    const handleDrawerSubmit = values => {
       const addedOpaqueMaterials = formValues.constructionSet?.opaqueMaterials; // array of objects
    
       const updatedMaterial = addedOpaqueMaterials.find(i => i.id === values?.opaqueMaterial?.id);
       // values?.opaqueMaterial is having updated object
        
       // Object.assign(updatedMaterial, values.opaqueMaterial); getting an error      
    };
    

    现在我想合并 values.Opaquematerial 对象到 addedOpaqueMaterials 哪一种是对象数组,实现这一点的最佳方法是什么?

    非常感谢

    2 回复  |  直到 5 年前
        1
  •  0
  •   CertainPerformance    5 年前

    而不是使用 .find ,使用 .findIndex 首先,这样就可以用新对象替换数组中的对象。(记住不要使用 Object.assign 在React中,当第一个参数是stateful时,因为这会导致状态突变)

    在尝试更新之前,还应该首先检查所有这些对象是否存在。

    if (!formValues.constructionSet || !values || !values.opaqueMaterial) {
      return;
    }
    const newMat = values.opaqueMaterial;
    const index = addedOpaqueMaterials.findIndex(mat => mat.id === newMat.id);
    if (index === -1) {
      // Add to the end of the existing array:
      const newOpaqueMaterials = [
        ...addedOpaqueMaterials,
        newMat
      ];
      // put newOpaqueMaterials into state
    } else {
      // Replace the object in the state array with the new object:
      const newOpaqueMaterials = [
        ...addedOpaqueMaterials.slice(0, index),
        newMat,
        ...addedOpaqueMaterials.slice(index + 1)
      ];
      // put newOpaqueMaterials into state
    }
    
        2
  •  1
  •   Andrew    5 年前

    这只是一个常规算法的挑战。不用想了。react对您的唯一要求是它必须是一个新数组。 Array#map 很好用。

    const materialExists = addedOpaqueMaterials.some(({id}) => id === values?.opaqueMaterial?.id)
    let updatedMaterial
    if (materialExists) {
        updatedMaterial = addedOpaqueMaterials.map(material => {
            if (material.id === values?.opaqueMaterial?.id) {
                return values.opaqueMaterial
            }
            return material
        })
    } else {
        updatedMaterial = [...addedOpaqueMaterials, values.opaqueMaterial]
    }