React 生命周期函数总结

我们使用 React 来开发项目时候,每个 react 组件都包含生命周期方法,我们可以在这些方法当中执行一些业务逻辑。生命周期方法包含了如下的几个阶段:

挂载:当组件实例被创建并插入 DOM 中时

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

更新:当组件的 props 或 state 发生变化时会触发更新

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

卸载: 当组件从 DOM 中移除时会调用

  • componentWillUnmount()

下图更加清晰地展示了组件在不同阶段调用的方法:

 

 

方法是否必须说明
render() 必须 render() 方法是 class 组件中唯一必须实现的方法,调用此方法才能把JSX内容渲染到页面上
constructor() 非必须 constructor(props),可以在构造函数里面初始化 state 或进行方法绑定
componentDidMount() 非必须 会在组件挂载后(插入 DOM 树中)立即调用,可以在里面发送 http 请求、设置定时器等操作
componentDidUpdate() 非必须 componentDidUpdate(prevProps, prevState, snapshot),会在更新后会被立即调用,但是首次渲染不会执行此方法。注意:在此方面里面调用 setState,应该避免出现死循环,可以将条件语句里面更新 state
componentWillUnmount() 非必须 会在组件卸载及销毁之前直接调用,可以在里面清除定时器、取消大的对象的引用等操作。注意:应避免调用setState()
shouldComponentUpdate() 非必须 shouldComponentUpdate(nextProps, nextState),根据 nextProps 和 nextState 这两个参数来判断当前组件是否可以更新
static getDerivedStateFromProps() 非必须 static getDerivedStateFromProps(props, state),会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容
getSnapshotBeforeUpdate() 非必须

getSnapshotBeforeUpdate(prevProps, prevState)在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期的任何返回值将作为参数传递给 componentDidUpdate()

getDerivedStateFromError() 非必须

static getDerivedStateFromError(error),会在后代组件抛出错误后被调用,一般用于错误捕获

componentDidCatch() 非必须

componentDidCatch(error, info),会在后代组件抛出错误后被调用,一般用于错误捕获

 

过时的生命周期方法

方法是否必须说明
UNSAFE_componentWillMount() 非必须 改方法在 render() 之前调用,之前名为 componentWillMount。该名称将继续使用至 React 17
UNSAFE_componentWillReceiveProps() 非必须 父组件重新渲染时候会调用此方法,之前名为 componentWillReceiveProps。该名称将继续使用至 React 17
UNSAFE_componentWillUpdate() 非必须 当组件收到新的 props 或 state 时,会在渲染之前调用此方法,之前名为 componentWillUpdate。该名称将继续使用至 React 17

posted on 2021-10-13 17:55  jeanneze  阅读(213)  评论(0编辑  收藏  举报

导航