In React, how to decide whether to use components componentWillReceiveProps or componentWillMount?

componentWillMount is called first when rendering

componentWillReceiveProps called for subsequent renderings

So - if I want to perform some action (for example, initialize some data in the store) when the component is displayed, where do I put this code? - Which depends on the missed passage from a higher level component.

The problem is that I do not know for sure whether the identifier will be initialized by the time the first render call. (Reliance is dependent on asynchronous data). So - I cannot put the code in componentWillMount. But if I put it in componentWillReceiveProps and then changed something upstream in the component chain so that the data runs synchronously, now my code in the WillReceiveProps component never runs. The motivation for this post is that I just did just that and now I have to reorganize a bunch of components.

It seems the only solution is to put the code in both methods.

There is no life-cycle method that is always called - for the first time and then. But how can you know for sure if your data on top-level components will necessarily be available by the time of the first rendering? Or in this case, definitely not. Or maybe you can be - but then you change it.

This life approach seems very fragile to me. Did I miss something? (Most likely).

+5
source share
1 answer

You already have the answer: put the code in both methods. However, I would suggest converting the details into both methods and using the state as your only source of truth.

componentWillMount () { this.checkAndUpdateState(this.props); } componentWillReceiveProps (nextProps) { this.checkAndUpdateState(nextProps); } checkAndUpdateState (props) { this.setState({ isLoaded: !!props.yourData }); } 
+3
source

Source: https://habr.com/ru/post/1234275/


All Articles