React 基础篇 (二)生命周期

60 阅读2分钟

生命周期官方文档

1. 16 版本之前

257c4362569fec92c188c57873ed584.png

React生命周期函数:

  • 组件首次加载完成的时候触发的函数:

    • constructor 首先会触发构造函数
    • componentWillMount 其次会触发,表示组件将要挂载
    • render 然后数据渲染
    • componentDidMount 组件加载完成(dom操作放在这里, 请求数据也放在这里)
  • 组件数据更新的时候触发的生命周期函数:

    • shouldComponentUpdate 首先触发,表示是否要更新数据,该方法里面必须为true01
    • componentWillUpdate 将要更新数据的时候触发02
    • render 数据渲染03
    • componentDidUpdate 数据更新完毕04
    • componentWillReceiveProps
    • componentWillReceiveProps (在父组件里面改变props传值的时候触发的:)
      • 在componentWillReceiveProps这个回调函数中,我们可以获取到就是props,通过this.props来获取,然后新的props则是通过函数的参数传入,在这里我们可以比较两个props从而对本组件的state作出安全的变更然后重新渲染我们的组件或者是触发子组件内的某些方法。

//componentWillReceiveProps方法中第一个参数代表即将传入的新的Props

componentWillReceiveProps(nextProps) {
    if (this.props.sharecard_show !== nextProps.sharecard_show){
        //在这里我们仍可以通过this.props来获取旧的外部状态
        //通过新旧状态的对比,来决定是否进行其他方法
        if (nextProps.sharecard_show){
            // todo
            
        }
    }
}

  • 组件销毁的时候触发的:
    • componentWillUnmount

2. 16.3 版本之后

16.3 版本之后.png

组件的生命周期

挂载

当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:

更新

当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:

卸载

当组件从 DOM 中移除时会调用如下方法:

错误处理

当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用如下方法:


class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error, info) {    
      // "组件堆栈" 例子:    
      //   in ComponentThatThrows (created by App)    
      //   in ErrorBoundary (created by App)    
      //   in div (created by App)    
      //   in App    
      logComponentStackToMyService(info.componentStack);  
  }
  
  render() {
    if (this.state.hasError) {
      // 你可以渲染任何自定义的降级 UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}