【问题标题】:REACT UPDATE A DATA反应更新数据
【发布时间】:2021-03-17 21:12:01
【问题描述】:

我在尝试更新位于 Themecontext 中的对象数组时遇到问题,我的问题是突变,我正在使用来自不变性助手的更新。问题是当我在我的特定元素中更新我的数组时,这会出现在我的对象的末尾。

这是我的代码:

function changeValueOfReference(id, ref, newValue) {

        const namevalue = ref === 'colors.primary' ? newValue : '#'; 
        console.warn(id);

        const data = editor;
        const commentIndex = data.findIndex(function(c) { 
          return c.id === id; 
        });

        const updatedComment = update(data[commentIndex], {styles: { value: {$set: namevalue} } })

      
        var newData = update(data, {
          $splice: [[commentIndex, 1, updatedComment]]
        });

        setEditor(newData);

这是我的结果:

注意:在我尝试实现以下代码之前,但这会改变最终数组并破坏我的测试:

 setEditor( prevState => (
          prevState.map( propStyle => propStyle.styles.map( eachItem => eachItem.ref === ref ? {...eachItem, value: namevalue}: eachItem ))
        ))

【问题讨论】:

    标签: arrays reactjs object updating


    【解决方案1】:

    嗯,我终于明白了这个问题:

    1 - commentIndex 总是引用到 0

    对我来说效果很好的解决方案:

    1 - 查找父级的索引

    2 - 找到孩子的索引

    3 - 添加一个数组 []

    styles : { value: {$set: namevalue} }  => styles :[ { value: [{$set: namevalue}] } ]
    

    任何其他方法都是惠康

    完整代码:

    function changeValueOfReference(id, referenceName, newValue) {
        const data = [...editor];
          const elemIndex = data.findIndex((res) => res.id === id);
          const indexItems = data
            .filter((res) => res.id === id)
            .map((re) => re.styles.findIndex((fil) => fil.ref === referenceName));
          const updateItem = update(data[elemIndex], {
            styles: {
              [indexItems]: {
                value: { $set: namevalue },
                variableref: { $set: [''] },
              },
            },
          });
          const newData = update(data, {
            $splice: [[elemIndex, 1, updateItem]],
          });
    
          setEditor(newData);
    }
    

    【讨论】: