Why should an ajax request be executed in componentDidMount components in React?

The handling documentation states that the ajax request must be triggered from the componentDidMount lifecycle event (see edit documents ).

Why is this event?

In most cases, when loading data using ajax, I want to display some loading panel, for example:

 componentDidMount() { this.setState({isLoading: true}); fetch(...) .then(...) .then(() => this.setState({isLoading: false}) } 

but this calls the render method 3 times (the initial render immediately after setting isLoading = true , and then isLoading = false

What happened to sending an ajax request from componentWillMount event?

+6
source share
2 answers

Well, isLoading: true can be part of the initial state, there is no need to set it after the component has made mount => only 2 visualizations, not 3.

According to https://github.com/reactjs/react-redux/issues/210 , the result of calling render only once from componentWillMount means that if setState is asynchronous after render , it will have no effect (if I understand the comments correctly) .

Iโ€™m not sure that there is a chance that the callback with setState can be executed before render , and thus the loading screen will not be visible, only the results, so sometimes it "works" (most likely in DEV), but actually it would be very difficult to debug the race condition ...

See also https://facebook.imtqy.com/react/tips/initial-ajax.html

+3
source

The point allows you to process the response component with the initial state so that you see the loading panel (load: true).

You can move the line: this.setState ({isLoading: true}) to componentWillMount (). Because the configuration state in the WillMount component will not restart your component. Your visualization method will receive an updated component.

0
source

All Articles