setState 没有更新 React 中的设置值

setState didn't update the set value in React

这是我尝试更新状态值的代码。我无法弄清楚为什么我的状态没有得到更新。我在每一行代码中添加了所有相应的控制台值。


handleFilter=(event)=>
  {
    console.log(this.state.answerStatus) // Before update 'all'
    let val= event.target.value === "answered";
    console.log(val); // true or false
    this.setState({answerStatus:val});
    console.log(this.state.answerStatus); // 'all'
  }

状态更新为 async

要在 setState 后查看更新后的值,请使用第二个参数,它带有回调函数并在那边发出控制台日志。

handleFilter = (event) => {
  console.log(this.state.answerStatus); // Before update 'all'
  let val = event.target.value === "answered";
  console.log(val); // true or false
  this.setState({ answerStatus: val }, () =>
    console.log(this.state.answerStatus)
  );
};

在 React 中 setState 是异步的,这意味着状态值不会在您调用 setState 后立即修改,这就是为什么您从 console.log.

Why is setState in reactjs Async instead of Sync?

React Docs

handleFilter = (event) => {
    console.log(this.state.answerStatus) // Before update 'all'

    let val= event.target.value === "answered";

    console.log(val); // true or false

    this.setState({answerStatus:val}, () => {
       console.log(this.state.answerStatus);
    });
    
  }