Use componentWillMount or componentDidMount lifecycle functions to request async in React

I read how to respond to the life cycle, and I'm a little confused. Some recommend using componentWillMount to call ajax:

https://hashnode.com/post/why-is-it-a-bad-idea-to-call-setstate-immediately-after-componentdidmount-in-react-cim5vz8kn01flek53aqa22mby

Calling setState on the DidMount component will call another render () call, and this can blur the layout.

and in other places it should not put ajax calls in componentWillMount:

https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d

... this function can be called several times before the initial render is called so that it can trigger several side effects. In this regard, it is not recommended to use this for any actions that cause side effects.

What is right?

+2
source share
3 answers

React documents recommended componentDidMountfor creating network requests

componentDidMount()called immediately after the component is installed. Initialization requiring DOM nodes should go here. If you need to download data from a remote endpoint, this is a good place to create a network request.

setState() , . , render() , .

componentWillMount:

. , .

"" , . componentWillMount setTimeout - . - , .

componentDidMount - :

  • DidMount , . , undefined , .
  • - , componentWillMount - , - , , . componentDidMount .
+3

componentDidMount - Ajax,

+1

ComponentDidMount is the place.

But if you have time to try to look at Redux and make requests in actions as your application grows, this will help a lot to manage the state of the application.

;)

0
source

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


All Articles