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