【问题标题】:ReactJS: setState() value is rendering in console.log but not updating in stateReactJS:setState() 值在 console.log 中呈现,但未更新状态
【发布时间】:2020-11-18 08:23:58
【问题描述】:

在这里,我遇到了 setState() 的小问题。我知道这个setState() 是一个asynchronous 函数。我也从SO example 中获得了一些示例,并且我在console.log() 中获得了我的价值,但这同样没有在状态更新。

我需要在此处更改什么以获得更新的state() 值。请给我任何建议。

在我的标签页代码中,state 值应更新为form 提交。

//代码

handleOnSubmitJoinUS(e) {
    e.preventDefault();
    const { name,  phone, email, comment, activeTab } = this.state;

    if (activeTab == 0 ) {

        this.setState({comment: "Message for : Becoming a team member"}, () => {
            console.log(this.state.comment);
        });

    } else if (activeTab == 1) {
        this.setState({comment: "Message for : Becoming a Vendor Partner"}, () => {
            console.log(this.state.comment);
        });

    } else {
        this.setState({comment: "Message for : Becoming a Designer Associates"}, () => {
            console.log(this.state.comment);
        });
    }
    
    
    const sendingMsgData = {
        name,  phone, email, comment
    }

    //attempt to login
    if (sendingMsgData.email && sendingMsgData.name && sendingMsgData.phone  != null  ) {
        this.setState({msg : "Thank you! we recieved your submission successfully, we will surely contact you within 24 hours"});
        window.setTimeout(function(){window.location.reload()}, 1000);
    } 
    this.props.sendingConsultation(sendingMsgData);
    
}

【问题讨论】:

  • 试试这个回调而不是 window.setTimeout stackoverflow.com/a/45186956/9277453
  • 您应该将尝试登录代码放在 setState 回调函数中,在其中 console.log 值。否则,您的登录代码尝试将在更新值之前运行。
  • @AlexNikonov 感谢您抽出宝贵时间。当然我也会检查这个。
  • @ÇağataySel 谢谢。我一定会记住这一点的。

标签: reactjs setstate


【解决方案1】:

正如你所说,setState 是异步的,所以函数的其余部分继续运行,在状态实际设置在this.state 之前完成所有的消息发送等等。对于您的原始代码,这意味着其余代码应该在那个 post-setState 回调中。

但是,comment 看起来根本不需要处于该状态,因为您是从 state.activeTab 派生的:

handleOnSubmitJoinUS(e) {
  e.preventDefault();
  const { name, phone, email, activeTab } = this.state;
  let comment;

  if (activeTab == 0) {
    comment = "Message for : Becoming a team member";
  } else if (activeTab == 1) {
    comment = "Message for : Becoming a Vendor Partner";
  } else {
    comment = "Message for : Becoming a Designer Associates";
  }

  const sendingMsgData = {
    name,
    phone,
    email,
    comment,
  };

  //attempt to login
  if (sendingMsgData.email && sendingMsgData.name && sendingMsgData.phone != null) {
    this.setState({ msg: "Thank you! we recieved your submission successfully, we will surely contact you within 24 hours" });
    window.setTimeout(function () {
      window.location.reload();
    }, 1000);
  }
  this.props.sendingConsultation(sendingMsgData);
}

如果您出于某种原因确实需要在state 中使用它,您可以在最后添加this.setState({comment})

【讨论】:

  • 哦,@AKX 非常感谢。我明白你的意思了。谢谢。
猜你喜欢
  • 2020-10-10
  • 2017-09-21
  • 1970-01-01
  • 2017-11-09
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
相关资源
最近更新 更多