Why componentWillMount is called after rendering?

后端 未结 1 1245
耶瑟儿~
耶瑟儿~ 2021-01-14 00:53

I am working with React and I am trying to understand the lifecycle. I am doing a componentWillMount method in order to get the props I need before

相关标签:
1条回答
  • 2021-01-14 01:17

    It's not weird at all. componentWillMount will fire before render, and in the first-pass you are invoking an action to get the dealers GetDealersActions.getDealers(); which is basically an async command. Since it is async, the component will render once before it gets data, and then again after the store publishes a changed event, which will re-trigger rendering.

    Here is an approximation of the sequence of actions happening in your example:

    1. componentWillMount invokes getDealers command (which is async)
    2. initial render with default component state
    3. Async operation completed in action creator and store is set with dealer data
    4. store publishes a changed event, which re-triggers rendering
    5. second render invoked with the dealer data in component state.

    The problem is that React will run it's lifecycle methods in a certain sequence, not caring about you invoking some async method. So basically you don't have a way to stop rendering just because you invoked a command to get the dealers. That is a limitation of react (or a feature), which surfaces when combined with async programming and you should accept it as is.

    If you accept the fact that React will render twice, you can utilize that in your favor, so on first render you could just show a loading indicator (e.g. a spinning wheel) and when the data loads you just display it in the second render.

    However, if you are not convinced and still want to avoid double-rendering in the initial load, you could do prefetching of the data before you mount the application component, which would ensure that initial data is loaded in the store before the first render, which would mean that you wouldn't have to invoke getDealers in componentWillMount since the data would already be in the store on the first render.

    As a reminder, double-rendering is not a significant performance problem, like it would be in Angular.js or Ember.js, since React is very efficient at DOM manipulation, but it could produce some UX issues if not handled properly.

    0 讨论(0)
提交回复
热议问题