React Lifecycle Methods diagram
总得来说:
- 挂载时调用
constructor
,更新时不调用 - 更新时调用
shouldComponentUpdate
和getSnapshotBeforeUpdate
,挂载时不调用 shouldComponentUpdate
在render
前调用,getSnapshotBeforeUpdate
在render
后调用- 请求放在
componentDidMount
里。
原因是constructor
无法放AJAX请求,是因为它会在SSR的时候会被调用,是会在服务端进行调用,服务端是拿不到数据的,更新时的钩子放请求会不断调用,可能会造成死循环,卸载时的钩子只会在生命周期结束的时候进行调用。