ReactJS:setState()值在console.log中呈现,但未更新状态

时间:2020-07-28 19:55:47

标签: reactjs setstate

在这里我遇到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);
    
}

1 个答案:

答案 0 :(得分:2)

正如您所说,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})