Why componentWillMount should not be used?

前端 未结 5 768
傲寒
傲寒 2020-12-14 16:07

Firing server call to fetch data in componentWillMount life cycle method a bad practice?

And why it is better to use componentDidMount.

5条回答
  •  时光说笑
    2020-12-14 16:30

    The way I understand it, one of the biggest reasons has to do with setting up the right expectations for the developers reading the code.

    If we use componentWillMount it's tempting to think that the fetch have time to happen, then the component "did" mount, and then the first render will happen. But that it not the case. If we do an async call (like an API call with Promises), the component will actually run render before the fetch can return and set the component state (or change the Redux state, or what ever).

    If we instead use componentDidMount, then it's clear that the component will render at least once before you get back any data (because the component already did mount). So, by extension, it's also clear that we have to handle the initial state in a way so that the component doesn't break on the first ("empty") render.

提交回复
热议问题