Why componentWillMount should not be used?

前端 未结 5 786
傲寒
傲寒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 16:28

    componentDidMount is the best place to put calls to fetch data, for two reasons:

    1. Using componentDidMount makes it clear that data won’t be loaded until after the initial render. You need to setup initial state properly, so you don’t get undefined state that causes errors.

    2. If you need to render your app on the server, componentWillMount will be called twice(on the server and again on the client), which is probably not what you want. Putting the data loading code in componentDidMount will ensure that data is only fetched from the client. Generally, you should not add side effects to componentWillMount.

提交回复
热议问题