【问题标题】:React component not reading this.props correctly反应组件未正确读取 this.props
【发布时间】:2018-03-07 15:31:57
【问题描述】:

我有一个 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 个计数,无论如何——意思是,当 props 的 pageNumber 值为 3 时,它打印为 2,props 的值为 4,它打印为 3,等等。这导致我在服务器端分页时获取不正确的帖子。

我怎样才能得到正确的值?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您正在从componentWillReceiveProps 函数调用getPosts。此时,组件原有的props还没有更新,所以在getPosts中访问this.props.pageNumber不会显示更新的props,应该将nextProps传递给getPosts函数,然后像访问一样

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 2016-11-01
        • 2020-08-06
        • 1970-01-01
        • 2021-01-05
        • 1970-01-01
        • 2017-01-21
        相关资源
        最近更新 更多