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 componentWillMount
orconstructor
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-rendering
which 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 componentWillMount
or 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 setState
will asynchronize, and componentWillMount
already 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?
source
share