Can I call the API in the WillMount component in React?

I am working to respond to the last year. The following convention concludes the API call in componentDidMount, retrieves the data, and setState after the data arrives. This ensures that the component has mounted and set the state, will lead to the re-rendering of the component, but I want to know why we cannot set the State to componentWillMountorconstructor

The official documentation states that:

componentWillMount () is called immediately before installation. This is called before render (), so setting the state in this method will not trigger re-rendering. Avoid introducing any side effects or subscription in this method.

he says setting state in this method will not trigger a re-renderingwhich I do not want when calling the API. If I can get the data and set it in a state (assuming that the API calls are really fast) in componentWillMountor in constructor, and the data is present in the first rendering, why do I want to re-render at all?

and if the API call is slow, then it setStatewill asynchronize, and componentWillMountalready returned, then I can install the State and re-renovation will occur.

All in all, I'm rather confused why we shouldn't make API calls in the constructor or component of WillMount. Can someone really help me understand how they react in this case?

+6
source share
3 answers

1. componentWillMount

componentWillMount.
,

componentWillMount () {
  // This will not cause additional re-render
  this.setState({ name: 'Andrej '});
}

componentWillMount () {
  fetch('http://whatever/profile').then(() => {
    // This in the other hand will cause additional rerender,
    // since fetch is async and state is set after request completes.
    this.setState({ name: 'Andrej '});
  })
}

.
.
.
2. API?

componentWillMount () {
  // Is triggered on server and on client as well.
  // Server won't wait for completition tho, nor will be able to trigger re-render
  // for client.
  fetch('...')
}

componentDidMount () {
  // Is triggered on client, but never on server.
  // This is good place to invoke API calls.
  fetch('...')
} 

, , ( ) .

+5

ComponentWillMount

, , , ,

, React , state , render , , - , ajax.


, .

, ajax , ajax , . / .


, . ajax .

, state, this.setState ( , ).

. API , , , . , . , . , ajax ref . , , state setState setter () .

, , API , , .

+2

If you only need data only at the first start, and if you are ok with this. You can set State synchronously by calling a callback.

eg:

componentWillMount(){
    this.setState({
                sessionId: sessionId,                
            }, () => {
                if (this.state.hasMoreItems = true) {
                    this.loadItems()   // do what you like here synchronously 
                }
            });
}
0
source

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


All Articles