Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

reactjs - Understanding initial state setting using react component lifecycle method

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use getDerivedStateFromProps, nobody forbids you to do that, but it's purpose is not for that. You should use it only for updating the internal state of the components depending on it's props changes. I would stick to componentDidMount, it's pretty good choice and the only one I see.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...