Why getDerivedStateFromProps is called after setState?

后端 未结 5 1608
别那么骄傲
别那么骄傲 2021-02-06 23:02

React introduced new static method getDerivedStateFromProps(props, state) which is called before every render method, but why? Calling it after prop change makes se

5条回答
  •  悲哀的现实
    2021-02-06 23:51

    I also got that issue. So I set another variable to check is that prop received for the first time.

    this.state={flag:true}
    

    In getderivedstatefromprops

    static getderivedstatefromprops(props, state){
       if(props.<*propName*> && flag){
          return({ props.<*propName*>, flag:false})
       }
    }
    

    if you want to use multiple props values you need to set your if statements (or any other logic) accordingly.

提交回复
热议问题