图解React生命周期

图片来自:https://segmentfault.com/a/1190000016494335


1、如图所示,组件一开始会调用constructor函数,进行state以及props的初始化赋值。

2、随后进入componentWillCount,componentWillCount只在第一次render前调用。

3、在第一次render,即初始化render后,调用componentDidMount。

4、当运行期间,props发生变化时,调用componetWillReciveProps,在render前调用。

5、随后调用shouldComponentUpdate,该方法如果返回false,可以阻止组件渲染。通过条件判断,可以减少重复渲染。

6、之后,调用componentWillUpdate方法,通知即将开始渲染更新,在render前。

7、render完成后,调用componentDidUpdate方法,通知组件属性更新完成。

8、组件销毁,则调用componentWillUnMount,此方法中可以释放一些定时器,避免内存泄露。

示例代码:

实例代码来自:菜鸟教程React 组件生命周期

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>React 实例</title>

<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>

<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>

<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>

</head>

<body>

<div id="example"></div>

<script type="text/babel">

class Button extends React.Component{

  constructor(props) {

      super(props);

      this.state = {data: 0};

      this.setNewNumber = this.setNewNumber.bind(this);

  }


  setNewNumber() {

    this.setState({data: this.state.data + 1})

  }

  render() {

      return (

         <div>

            <button onClick = {this.setNewNumber}>INCREMENT</button>

            <Content myNumber = {this.state.data}></Content>

         </div>

      );

    }

}

class Content extends React.Component{


  componentWillMount() {

      alert('Component WILL MOUNT!')

  }

  componentDidMount() {

       alert('Component DID MOUNT!')

  }

  componentWillReceiveProps(newProps) {

        console.log('Component WILL RECEIVE PROPS!')

  }

  shouldComponentUpdate(newProps, newState) {

        return true;

  }

  componentWillUpdate(nextProps, nextState) {

          alert('Component WILL UPDATE!');

        console.log('Component WILL UPDATE!');

  }

  componentDidUpdate(prevProps, prevState) {

          alert('Component DID UPDATE');

        console.log('Component DID UPDATE!')

  }

  componentWillUnmount() {

          alert('Component WILL UNMOUNT!');

         console.log('Component WILL UNMOUNT!');

  }

    render() {

      return (

        <div>

          <h3>{this.props.myNumber}</h3>

        </div>

      );

    }

}

ReactDOM.render(

   <div>

      <Button />

   </div>,

  document.getElementById('example')

);

</script>

</body>

</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,529评论 1 33
  • 使用 create-react-app 快速构建 React 开发环境 项目的目录结构如下: React JSX ...
    majun00阅读 523评论 0 0
  • 个人笔记, 转载请注明转载自 szhshp的第三边境研究所 Refs and the DOM In the t...
    szhielelp阅读 1,503评论 0 1
  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 1,058评论 0 1
  • 真的好喜欢小孩,也会想过自己生一个,可是给孩子选爸这个问题一时半会儿还不能靠我的主观意识解决。并且看着别人生孩子的...
    月半out妹阅读 753评论 2 0