reactjs - In React how to decide whether to use componentWillReceiveProps or componentWillMount? -
componentwillmount called once @ first render
componentwillreceiveprops called subsequent renders
so - if want action (e.g. initialise data in store) when component rendered put code? - depends on prop passed in higher level component.
the problem don't know sure if prop initialised time first render called. (the prop depends on asynchronous data). - can't put code in componentwillmount. if put in componentwillreceiveprops , change higher component chain data fulfilled synchronously code in componentwillreceiveprops never run. motivation post did , have refactor bunch of components.
it seems solution put code in both methods.
there no lifecycle method called - first time , subsequent. how can know sure if data in top level components available time of first render? or matter not. or maybe can - change this.
this lifecyle approach seems fragile me. have missed something? (most likely).
you have answer: put code in both methods. however, i'd suggest convert props state in both methods, , use state single source of truth.
componentwillmount () { this.checkandupdatestate(this.props); } componentwillreceiveprops (nextprops) { this.checkandupdatestate(nextprops); } checkandupdatestate (props) { this.setstate({ isloaded: !!props.yourdata }); }
Comments
Post a Comment