州默认值
state = {
moveType: {
value: 0,
open: false,
completed: false
}
};
//回调更新新状态
let step = 'moveType';
let val = 3; // new value
let newObj = { ...this.state[step], value: val };
console.log(newObj);
this.setState({[step]: newObj }, function () {console.log(this.state);});
console.log(newObj)
显示正确的新值,但this.state
仍显示旧值..你能告诉我我做错了吗?
答案 0 :(得分:2)
在反应中设置状态是非常敏感的事情。
我以前的最佳实践总是手动控制对象深度合并并使用this.setState(state => { ... return new state; })
类型的调用,如下例所示:
this.setState(state => ({
...state,
[step]: { ...(state[step] || {}), ...newObj },
}), () => console.log(this.state));
SNIPPET UPDATE开始
[step]: { ...state[step], ...newObj }
更改为:
[step]: { ...(state[step] || {}), ...newObj }
正确处理案例时,状态还没有此step
键
SNIPPET UPDATE结束
事情就是,当你使用this.state
(在let newObj = { ...this.state[step]
中)时,它可能有一个过时的值,因为状态的一些待定(尚未合并),你已经调用几毫秒之前。
因此我建议使用回调方法:this.setState(state => { ... use state and return new state;})
,以保证您使用的state
具有最新值