试图了解React的生命周期阶段
问题描述:
我对我的React应用中生命周期阶段的顺序感到困惑。我有以下类:试图了解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()
是使用终极版
答
setState
是异步调用Ajax。所以你必须使用回调:
this.setState({skip: (this.state.skip + 5)},() => {
console.log(this.state.skip);
})