Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

从后台获取数据一定要放在componentDidMount里面调用,为什么不能在constructor或者componentWillMount里面调用?有什么不同? #48

Open
zyb970821 opened this issue Jun 22, 2021 · 1 comment

Comments

@zyb970821
Copy link

No description provided.

@yinyinnnn
Copy link

从后台获取数据一定要放在componentDidMount里面调用,为什么不能在constructor或者componentWillMount里面调用?有什么不同?

从后台获取数据一定要放在componentDidMount里面调用原因在于如果你要获取外部数据并加载到组件上,只能在组件"已经"挂载到真实的网页上时,其它情况是不能加载到组件的。

componentDidMount方法中的代码,是在组件已经完全挂载到网页上才会调用被执行,所以可以保证数据的加载。此外,在这方法中调用setState方法,会再次渲染。

constructor被调用是在组件准备要挂载的最一开始,所以组件尚未挂载到网页上。

componentWillMount方法的调用在constructor之后,在render之前,在这方法里的代码调用setState方法不会触发重复渲染,所以它一般不会用来作加载数据。

一般的从后台获取的数据,都会与组件要用的数据加载有关,所以都在componentDidMount方法里面调用。与组件上的数据无关的加载,也可以在constructor里,但constructor是作组件state初始化工作,并不是用来加载数据的,所以调用都会集中在componentDidMount方法里。

@Dogtiti Dogtiti removed the Cbayel label May 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants