这是我的初始状态:

this.state = {
  requiredError: false,
  addressSelectError: false,
  recipientError: false,
  open: false,
};


这是我的问题所在:

processCheckout () {
    this.setState({
      requiredError: true,
      addressSelectError: true,
      recipientError: true,
    }, () => {
      console.log('required error', requiredError);
      console.log('address error', addressSelectError);
      console.log('recipient error', recipientError);
    })
}


我已将它们全部设置为true,但控制台仍记录为false:

javascript - ReactJS:setState和回调后状态未更新-LMLPHP

我已经使用了回调,但是它仍然没有改变。有什么帮助吗?

我在按钮的processCheckout()上调用onClick()函数。

编辑:我已经尝试过控制台登录渲染,并且它们都是true

最佳答案

没有看到完整的代码,我假设您已经声明了变量
requiredError, addressSelectError and recipientError在您课堂上的某个地方:

在回调中,尝试直接访问this.state

processCheckout() {

    this.setState(
      {
        requiredError: true,
        addressSelectError: true,
        recipientError: true
      },
      () => {
        console.log("required error", this.state.requiredError);
        console.log("address error", this.state.addressSelectError);
        console.log("recipient error", this.state.recipientError);
      }
    );
  }

关于javascript - ReactJS:setState和回调后状态未更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55662087/

10-11 03:54
查看更多