Skip to content

React.Component – React

React Lifecycle Methods diagram

总得来说:

  1. 挂载时调用constructor,更新时不调用
  2. 更新时调用shouldComponentUpdategetSnapshotBeforeUpdate,挂载时不调用
  3. shouldComponentUpdaterender前调用,getSnapshotBeforeUpdaterender后调用
  4. 请求放在componentDidMount里。

原因是constructor无法放AJAX请求,是因为它会在SSR的时候会被调用,是会在服务端进行调用,服务端是拿不到数据的,更新时的钩子放请求会不断调用,可能会造成死循环,卸载时的钩子只会在生命周期结束的时候进行调用。