Kai*_*ary 3 reactjs react-native react-redux
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在调用这个函数。因为它正在增加count价值,但是当我访问它时,它会返回以前的值。我想在同一个函数中访问最新的更新值,我应该怎么做。
如何在同一函数中访问最新的状态值
pwo*_*laq 10
如此处所述, React 具有附加callback参数。
此外,当您想使用当前值改变您的状态时,您应该使用函数版本:
this.setState(currentState => ({ count: currentState.count + 1 }), () => {
console.log(this.state.count);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7878 次 |
| 最近记录: |