【发布时间】: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 谢谢。我一定会记住这一点的。