为什么对状态所做的更改不会在componentDidMount生命周期中显示?

时间:2020-10-09 21:28:59

标签: reactjs react-lifecycle

我正在使用React构建一个应用程序,并且在我的主页上,我在componentDidMount生命周期中设置了状态:

export default class HomePage extends Component {
  state = {
    posts: [],
    token: '',
  };

  //Display posts when homepage renders
  componentDidMount() {
    //If token exists, run lifecycle event
    if (this.props.location.state.token) {
      this.setState({ token: this.props.location.state.token });
    }
    Axios.get('http://localhost:3000/api/posts/all')
      .then((req) => {
        this.setState({ posts: req.data });
      })
      .catch((err) => {
        console.log(err.message);
        throw err;
      });
    console.log(this.state);
  }

但是,当我在生命周期方法的末尾运行控制台日志时,它显示帖子和令牌仍然为空。我知道他们正在填充,因为req.data中的帖子显示在我的JSX中。当我在方法内部进行控制台登录时,为什么显示状态为空?

1 个答案:

答案 0 :(得分:2)

反应setState是异步的!

  • 反应不能保证状态更改立即生效。
  • setState()并不总是立即更新组件。
  • 将setState()视为请求而不是立即命令来更新组件。
this.setState((previousState, currentProps) => {
    return { ...previousState, foo: currentProps.bar };
});