React的生命周期

2020-11-07  本文已影响0人  大南瓜鸭

React的生命周期分为四个部分,分别是挂载时、更新时、卸载时、错误处理。他们的生命周期调用顺序如下:

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

1. constructor()

constructor(props) {
  super(props);
  this.state = {
    text:"初始值"
  };
}

2. static getDerivedStateFromProps(props, state)

state = {
    color: '',
    prevPropsColor: ''
  }
  // 因为这个生命周期是静态方法,同时要保持它是纯函数,不要产生副作用。
  // 纯函数:输入一定,输出一定确定,不能使用随机数
static getDerivedStateFromProps (props, state) {
    console.log(props)
    console.log(state)
    // 把传入的 prop 值和之前传入的 prop 进行比较。
    if (props.color !== state.prevPropsColor) { 
      return {
        color: props.color,
        prevPropsColor: props.color
      }
    }
    return null
  }
}

3. render()

render()方法是必需的。当他被调用时,他将计算this.propsthis.state,并返回以下一种类型:

当返回null,false,ReactDOM.findDOMNode(this)将会返回null,什么都不会渲染。

4. componentDidMount()

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

1. static getDerivedStateFromProps()

2. shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate (nextProps, nextState) {
  // 默认值为true
  return false // 组件不会触发更新函数,也就是不会触发render以及以后的生命周期钩子
  }
  componentDidUpdate () {
    console.log('father', 'componentDidUpdate')
  }

3. render()

4. getSnapshotBeforeUpdate(prevProps, prevState)

5. componentDidUpdate()

componentDidUpdate(prevProps) {
  // 典型用法(不要忘记比较 props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

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

componentWillUnmount()

错误处理:当渲染过程,生命周期,或子组件的构造函数中抛出错误时

1.static getDerivedStateFromError(error)

会在渲染阶段调用

static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染可以显降级 UI
    return { hasError: true };
  }

2.componentDidCatch(error, info)

会在“提交”阶段被调用

componentDidCatch(error, info) {
    // "组件堆栈" 例子:
    //   in ComponentThatThrows (created by App)
    //   in ErrorBoundary (created by App)
    //   in div (created by App)
    //   in App
    logComponentStackToMyService(info.componentStack);
  }

你可以使用此生命周期图谱作为速查表。在下述列表中,常用的生命周期方法会被加粗。其余生命周期函数的使用则相对罕见

生命周期图谱.png
上一篇 下一篇

猜你喜欢

热点阅读