[英]How to get the updated state in setState callback?
I have a code scenario where I need get the updated state in the setState callback.我有一个代码场景,我需要在 setState 回调中获取更新的状态。 Like below :
像下面这样:
this.setState({name : "xyz"}, () => {
//I want the updated state here where I need to get the this.state.name should be "xyz"
})
To get the updated state after setting a state is same as described in question.在设置状态后获取更新的状态与问题中描述的相同。
this.setState({name : "xyz"}, () => {
console.log(this.state.name)
});
I asked this question as I had some issues in my function and was unable to get the updated state.我问这个问题是因为我的函数有一些问题并且无法获得更新的状态。
Use componentDidUpdate() to get updated state and props values.使用 componentDidUpdate() 获取更新的 state 和 props 值。
componentDidUpdate(prevProps, prevState) {
console.log(this.state, prevState);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.