Reactjs 反应组件未正确读取此.props

Reactjs 反应组件未正确读取此.props,reactjs,Reactjs,我有一个react组件,它从父组件App.js接收道具。这是正确的。我可以控制台.log()执行以下操作: console.log()正确显示了此处的道具: {pageNumber: 2, loggedIn: true} 但是,在我的getPosts()方法中,我阅读了this.props: getPosts() { console.log("in post list and page is" + this.props.pageNumber) } 它会打印: in post list a

我有一个react组件,它从父组件App.js接收道具。这是正确的。我可以控制台.log()执行以下操作:

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个计数,不管怎样——这意味着,当props的页码值为3时,它打印为2,props的值为4,它打印为3,等等。这导致我在分页服务器端时获取错误的帖子


如何获取正确的值?

您正在从
组件willreceiveprops
函数调用
getPosts
。此时,组件的原始道具尚未更新,因此在
getPosts
中访问
this.props.pageNumber
不会显示更新的道具,您应该将nextrops传递给getPosts函数,然后像

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

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

您正在从
组件willreceiveprops
函数调用
getPosts
。此时,组件的原始道具尚未更新,因此在
getPosts
中访问
this.props.pageNumber
不会显示更新的道具,您应该将nextrops传递给getPosts函数,然后像

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

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

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

组件将接收道具(下一步)

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


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

组件将接收道具(下一步)

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