I am very new to react and as of now, I am trying to understand lifecycle
methods.
I have a scenario in which the moment users logs in, the home page should display user specific data.
So the moment user logs in I should set state of an application based on response from API(fetches user specific data).
So I want to set state first (based on response
) then render on real DOM
. Now I thought I should use getDeriveStatefromprops
for this purpose because it is just called before render()
. So, I can call API and then set state then finally render. But I read that it is not recommended to cause side-effects(make api call etc.) in this method. So naturally I am left with componentDidMound()
, where I can cause side effects.
My question is if I want to first get API response then render based
on that then why can't I use getDerivedStateFromProps, why I have to
use componentDidMount?
And what if fetch API call too much time, so will the initial render
of home page will be based on initial state in constructor and when i
get response back, then user specific data is displayed?
PS: I have researched a lot for around a day but couldn't get or understand the real reason for this. As I am new to react , a little less technical sounding answer is much appreciated.
question from:
https://stackoverflow.com/questions/66059206/understanding-initial-state-setting-using-react-component-lifecycle-method 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…