ReactJS 状态更新和即时访问

时间:2021-04-01 05:59:46

标签: reactjs react-state-management

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 值可能保持不变。

我的假设正确吗?

1 个答案:

答案 0 :(得分:1)

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

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