React 生命周期

943 阅读1分钟

componentWillMount

componentWillMount会在render方法之前执行,如果在componentWillMount中执行setState组件会更新state,但组件只会渲染一次。这是无意义的执行,初始化的state都可以放在this.state。

  state = {
      title: 'title'
  }
  componentWillMount() {
    this.setState({
      title: 'hello world!'
    })
  }
  render() {
    const {title} = this.state
    //这里只会打印 render, hello world,不会打印 render title
    console.log("render", title)
    return (
      <Fragment>
        <h1>{title}</h1>
      </Fragment>
    );
  }

这里如果在componentWillMount里执行异步方法获取数据,有可能发生内存泄漏的问题。 参考:juejin.cn/post/684490…

componentDidMount

componentDidMount会在render方法之后执行

componentWillReceiveProps

如果是当前的state更新不会触发此生命周期。

如果组件是由父组件更新props而更新的,那么会在执行componentWillReceiveProps方法。此方法可以作为react props传入后,渲染之前setState的机会。在此方法调用setState是不会二次渲染的。

shouldComponentUpdate

它接收需要更新的props和state让开发者增加必要额条件判断,让其在需要的时候更新,不需要时不更新。返回false的话会阻止继续更新。

componentWillUpdate 和 componentDidUpdate

对应更新过程中渲染前后的时刻。componentWillMount方法提供需要更新的props和state,componentDidUpdate提供更新前的props和state。 不能再componentWillUpdate里调用state,至于为啥我还没看到那里。。。

componentWillUnmount

卸载前的状态。

整体流程

//初始化
constructor -> 
componentWillMount -> 
render -> 
componentDidMount-> 
...状态更新 
-> componentWillUnmount

//state|props更新
componentWillReceiveProps (props 更新触发,当前组件state更新不触发)->
shouldComponentUpdate(可以return false阻止此次更新) -> 
componentWillUpdate(nextProps 要更新的props, nextState 要更新的state) -> 
render -> 
componentDidUpdate(更新前的state和props)