这个问题在这里已经有了答案:
Why calling react setState method doesn't mutate the state immediately?
(7 个回答)
setState doesn't update the state immediately
(15 个回答)
3年前关闭。
class Signup extends React.Component {
constructor() {
super();
this.state = { count: 0 }
}
hndlChange() {
//here it's okay, It increasing count value
this.setState({ count: this.state.count + 1 });
//but here it printing previous value
console.log(this.state.count);
}
}
我正在调用这个函数。随着它的增加
count
value 但是当我访问它时它返回以前的值。我想在同一个函数中访问最新的更新值,我应该怎么做。如何在同一函数中访问最新状态值
最佳答案
如前所述 here React 有额外的 callback
范围。
此外,当您想使用当前值改变您的状态时,您应该使用函数版本:
this.setState(currentState => ({ count: currentState.count + 1 }), () => {
console.log(this.state.count);
});
关于reactjs - 如何在用于设置状态值的同一函数中访问更新的状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319251/