【问题标题】:Trying to understand the lifecycle stages of React [duplicate]试图了解 React 的生命周期阶段 [重复]
【发布时间】:2017-11-02 09:38:27
【问题描述】:

我对 React 应用程序中生命周期阶段的顺序感到困惑。我有以下课程:

constructor(props) {
  super(props);

  this.state = {
    skip: 0
  }

}

fetchMoreArticles() {
  this.props.dispatch(fetchArticles(this.state.skip))
  this.setState({skip: (this.state.skip + 5)})
  console.log(this.state.skip); //This outputs 0 on page refresh???
}

componentDidMount() {
  this.fetchMoreArticles()
}

当我写入控制台时(请参阅fetchMoreArticles()),我希望输出为 5,但它是 0。有人可以解释原因吗?

注意:fetchArticles() 是一个使用 Redux 的 ajax 调用

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    setState 是异步的。所以你必须使用回调:

    this.setState({skip: (this.state.skip + 5)}, () => {
        console.log(this.state.skip);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-09
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2013-05-05
      • 2016-08-05
      • 2021-10-18
      相关资源
      最近更新 更多