变异嵌套对象

问题描述 投票:2回答:3

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

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不编译。我该如何解决这个问题?提前致谢!

javascript reactjs
3个回答
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}
        }))
    }));
};

2
投票

你可以覆盖qazxsw poi键并传播qazxsw poi

dataGrid

0
投票

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

step.dataGrid

编辑:将isDraggable = () => { this.setState(prevState => { const steps = prevState.stepsData.map(step => { return { ...step, dataGrid: { ...step.dataGrid, static: !step.dataGrid.static } } }); return { stepsData: steps }; }) }; 更改为其函数回调形式以响应T.J.克劳德的评论。

© www.soinside.com 2019 - 2024. All rights reserved.