As far as I could see, the only thing a componentWillMount
can do and a constructor
cannot is to call setState
.
componentWillMount() {
setState({ isLoaded: false });
}
Since we have not called render
yet, a setState
in componentWillMount
will prepare the state object before we enter the first render()
pass. Which is essentially the same thing a constructor
does:
constructor(props) {
super(props);
this.state = { isLoaded: false };
}
But I see another use case where componentWillMount
is useful (on server side).
Let's consider something asynchronous:
componentWillMount() {
myAsyncMethod(params, (result) => {
this.setState({ data: result });
})
}
Here we cannot use the constructor
as assignment to this.state
won't trigger render()
.
What about setState
in componentWillMount
? According to React docs:
componentWillMount()
is invoked immediately before mounting occurs. It
is called before render(
), therefore setting state in this method will
not trigger a re-rendering. Avoid introducing any side-effects or
subscriptions in this method.
So, here I think React will use the new state value for the first render and avoids a re-render.
Question 1: Does this means, inside componentWillMount
, if we call setState
in an async method's callback (can be a promise callback), React blocks initial rendering until the callback is executed?
Having this setup on client-side (yes I see that use case in server-side rendering), if I assume the above is true, I will not see anything until my asynchronous method completes.
Am I missing any concepts?
Question 2: Are the any other use cases that I can achieve with componentWillMount
only, but not using the constructor
and componentDidMount
?
question from:
https://stackoverflow.com/questions/40828004/constructor-vs-componentwillmount-what-a-componentwillmount-can-do-that-a-const 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…