react 生命周期

1. 组件初始化触发

执行顺序:constructor > UNSAFE_componentWillMount > render > componentDidMount

  1. 构造函数 constructor
    常用于定义 state 对象、为自定义方法绑定 this
constructor(props) {
    console.log("constructor 周期");
    super(props);
    this.state = {
      id: "100",
      name: "小明",
    };
  }
  1. UNSAFE_componentWillMount,render 函数渲染前触发
    常用于获取后端接口请求数据,接收参数,修改 state
UNSAFE_componentWillMount(nextProps, nextState, nextContext) {
    console.log("UNSAFE_componentWillMount 周期");
  }
  1. 渲染函数 render,组件正在渲染
    常用于定义 dom 元素和组件,一般不在内部书写业务逻辑
render() {
    console.log("render 周期");
    return (
      <>
        {this.state.id}
        {this.state.name}
      
    );
  }
  1. componentDidMount,render 函数渲染后触发
    常用获取 DOM 节点后的后续的操作
componentDidMount() {
    console.log("componentDidMount 周期");
  }

2. 组件更新触发

执行顺序:UNSAFE_componentWillReceiveProps > shouldComponentUpdate > UNSAFE_componentWillUpdate > render > componentDidUpdate

  1. UNSAFE_componentWillReceiveProps,当组件从父组件中接收参数,且父组件的state被修改后(此修改不包括第一次组件初始化的时候)会触发此组件中的这个生命周期
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    console.log("UNSAFE_componentWillReceiveProps 周期");
  }
  1. shouldComponentUpdate,state 修改后,组件渲染前触发,决定是否使用新数据渲染组件,必须 return
    return true 时,不阻止组件渲染,继续执行下面的生命周期
    return false 时,阻止组件渲染,不执行下面的生命周期
shouldComponentUpdate(nextProps, nextState, nextContext) {
    console.log("shouldComponentUpdate 周期");
    return true;
    // return false;
  }
  1. UNSAFE_componentWillUpdate,render 渲染前触发
UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) {
    console.log("UNSAFE_componentWillUpdate 周期");
  }
  1. render,组件渲染时触发
render() {
    console.log("render(渲染函数) 周期");
    return (
      <>
        
{ this.setState({ id: "10000000000", name: "改变state", }); }} > Child1
{this.state.id} {this.state.name}
); }
  1. componentDidUpdate,render 渲染后触发
componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate 周期");
  }

3. 组件卸载触发

componentWillUnmount 组件卸载时触发

componentWillUnmount() {
    console.log("componentWillUnmount 周期");
  }

你可能感兴趣的:(react 生命周期)