最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do i use componentWillReceiveProps() correctly? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to update a child ponent as soon as it recieves new props. However, ponentWillReceiveProps() in my child ponent is called before the props have actually updated. After reading this article i do understand why but it doesn't explain me how to solve my problem.

How do i call ponentWillReceiveProps() after the props have updated?

Right now i'm cheating my way around it by letting a timeout run which waits for the actual update, but i really don't like this solution.

  ponentWillReceiveProps(){
   var timeOut = setTimeout(() => this.loadPosts(), 100)
  },

Thanks id advance!

I'm trying to update a child ponent as soon as it recieves new props. However, ponentWillReceiveProps() in my child ponent is called before the props have actually updated. After reading this article i do understand why but it doesn't explain me how to solve my problem.

How do i call ponentWillReceiveProps() after the props have updated?

Right now i'm cheating my way around it by letting a timeout run which waits for the actual update, but i really don't like this solution.

  ponentWillReceiveProps(){
   var timeOut = setTimeout(() => this.loadPosts(), 100)
  },

Thanks id advance!

Share Improve this question asked Jan 4, 2017 at 0:14 Jonas BergnerJonas Bergner 1,7436 gold badges18 silver badges22 bronze badges 1
  • just pass prop to child ponent inside render. – Khalid Azam Commented Jan 4, 2017 at 7:41
Add a ment  | 

2 Answers 2

Reset to default 8

Is it necessary to call ponentWillReceiveProps after the props have updated? Or can you use the nextProps argument?

Eg. if you rewrite as:

ponentWillReceiveProps(nextProps){
  this.loadPosts(nextProps)
},

and then of course also rewrite the signature of loadPosts to allow manually passing in props:

loadPosts(props = this.props){
  // do something with props
  ...
}

Use ponentDidUpdate(prevProps, prevState). When it's called, two arguments are passed: prevProps and prevState. This is the inverse of ponentWillUpdate. The passed values are what the values were, and this.props and this.state are the current values.

发布评论

评论列表(0)

  1. 暂无评论