变异嵌套对象

时间:2018-03-06 09:35:21

标签: javascript reactjs

我试图在将对象设置为如下状态之前不改变对象内的对象:

isDraggable = () => {
        let steps = [...this.state.stepsData];

        steps = steps.map(step => {
            return {
                ...step,
                dataGrid.static: !step.dataGrid.static 
            }
        });

        this.setState({stepsData: steps})
 };

对象结构如下所示:

{
 stepsData:[{
  dataGrid: {
   x: ...
   y: ...
   static: true
  }
 }]
}

此行dataGrid.static: !step.dataGrid.static无法编译。我该如何解决这个问题?提前谢谢!

3 个答案:

答案 0 :(得分:4)

您需要克隆dataGrid引用的对象。另请注意,must use the function callback version of setState when you're setting state based on state

isDraggable = () => {
    this.setState(prevState => {
        return {stepsData: prevState.steps.map(step => {
            return {
                ...step,
                dataGrid: {...step.dataGrid, static: !step.dataGrid.static}
            };
        })};
    });
};

或更浓缩但可能不那么明确:

isDraggable = () => {
    this.setState(prevState => ({
        stepsData: prevState.steps.map(step => ({
            ...step,
            dataGrid: {...step.dataGrid, static: !step.dataGrid.static}
        }))
    }));
};

答案 1 :(得分:2)

您可以覆盖dataGrid密钥并展开step.dataGrid

isDraggable = () => {
    this.setState(prevState => {

        const steps = prevState.stepsData.map(step => {
            return {
                ...step,
                dataGrid: {
                    ...step.dataGrid,
                    static: !step.dataGrid.static
                }
            }
        });

        return { stepsData: steps };
    })
};

答案 2 :(得分:0)

不幸的是,您必须取消想要更改的对象的每一层,例如:

isDraggable = () => {
  this.setState(state => {
    return state.stepsData.map(step => {
      const { dataGrid } = step;

      return {
        ...step,
        dataGrid: {
          ...dataGrid,
          static: !dataGrid.static
        }
      };
    });
  });
};

编辑:将setState更改为功能回调表单以响应T.J.克劳德的评论。