【问题标题】:ReactJS state update and immediate accessReactJS 状态更新和立即访问
【发布时间】:2021-04-01 05:59:46
【问题描述】:
onContactChange = (contactInfo) => {
if (!this.state.isRecipientSelected) {
  this.setState({ ...this.state, isRecipientSelected: true });
}
if (contactInfo.selectedContactAccount.type && this.state.isRecipientSelected) {
  //...

在上面的代码段中,isRecipientSelected 设置为 True,然后立即在下一个 if 子句的条件中访问其值。在 ReactJs setState 是异步的,所以我假设当立即访问第二个 if 子句中的值时 isRecipientSelected 值可能保持不变。

我的假设正确吗?

【问题讨论】:

    标签: reactjs react-state-management


    【解决方案1】:

    是的。由于 setState 是一个同步函数,所以最好在 setState 中使用一个回调函数,该回调函数只有在状态设置后才会被调用。在你的情况下:

    if (!this.state.isRecipientSelected) {
      this.setState({ ...this.state, isRecipientSelected: true },function(){
          //Rest of the code
       }
    );
    }
    

    【讨论】:

    • onContactChange = (contactInfo) => { let recipientSelected = this.state.isRecipientSelected; if (!recipientSelected) { recipientSelected = true; this.setState({ ...this.state, isRecipientSelected: recipientSelected }); } if (contactInfo.selectedContactAccount.type && recipientSelected) { 感谢确认我的假设,在这里我使用新变量修复了它。正如您所提到的,使用回调将是设置状态后需要完成的事情的理想选择。
    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 2020-02-16
    • 2015-03-23
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2016-11-16
    • 2019-11-15
    相关资源
    最近更新 更多