React组件没有正确读取this.props

时间:2017-09-26 11:59:56

标签: reactjs

我有一个react组件,它接收来自它的父母App.js的道具。这工作正常。我可以console.log()这个:

componentWillReceiveProps(props) {
  console.log(props);
  this.getPosts()
}

console.log()在这里正确显示了道具:

{pageNumber: 2, loggedIn: true}

但是,在我的getPosts()方法中,我从this.props读取了

getPosts() {
  console.log("in post list and page is" + this.props.pageNumber)
}

它打印出来:

in post list and page is 1

它始终落后于1个计数,无论是什么 - 意思是,当道具的pageNumber值为3时,它打印为2,props的值为4,打印为3,等等。这导致我在分页服务器端时获取不正确的帖子。

如何获得正确的值?

2 个答案:

答案 0 :(得分:2)

您正在通过getPosts功能调用componentWillReceiveProps。此时,组件的原始道具尚未更新,因此访问this.props.pageNumber中的getPosts并未显示更新的道具,您应将nextProps传递给getPosts函数,然后像

一样访问它
componentWillReceiveProps(nextProps) {
  console.log(nextProps);
  this.getPosts(nextProps);
}

getPosts(nextProps) {
    console.log("in post list and page is" + nextProps.pageNumber)
}

答案 1 :(得分:1)

您收到的

道具是下一个新道具,而this.props尚未在此生命周期阶段更新。你可能应该直接将道具传递给getPosts(props.pageNumber)而不是

https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops componentWillReceiveProps(nextProps)

  

在安装的组件之前调用componentWillReceiveProps()   收到新的道具。如果您需要更新状态以响应   prop更改(例如,重置它),您可以比较this.props   和nextProps并使用this.setState()执行状态转换   这种方法。

相关问题