简体   繁体   English

如何在 setState 回调中获取更新的状态?

[英]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.

相关问题 ReactJS状态未更新在setState回调中 - ReactJS state not updated In setState callback ReactJS:setState和回调后状态未更新 - ReactJS: state not updated after setState and callback 使用 setState 时如何立即更新 state? - How do I get updated state immediately when using setState? React setState()在回调上不返回更新状态 - React setState() doesn't return updated state on callback react setState 回调没有更新状态 - react setState callback doesn't have the updated state 如何从回调方法中获取 state 的更新值? - How to get the updated value of a state from a callback method? react js无法在setState回调function中获取更新值 - react js cannot get updated value in setState callback function 如何访问已调用setState的函数体中的更新状态? - How to access the updated state in the body of a function that has already called setState? 如何在使用反应挂钩的 setState 方法之后访问更新的 state? - How to access the updated state after setState method with react hooks? React-还有另一种处理更新状态的方法,而不是在setState方法的回调部分中对所有函数进行硬编码? - React - there is an another way to handle updated state rather than hardcoding all functions it in the callback part of the setState method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM