gpt4 book ai didi

javascript - 改变嵌套对象

转载 作者:行者123 更新时间:2023-12-02 08:08:37 25 4
gpt4 key购买 nike

在将对象设置为这样的状态之前,我尽量不改变对象中的对象:

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

最佳答案

您需要克隆 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}
}))
}));
};

关于javascript - 改变嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49127555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com