zoukankan      html  css  js  c++  java
  • React 更新阶段的生命周期 componentWillReceiveProps->shouldComponentUpdate->componentWillUpdate

    除了挂载阶段,还有一种“更新阶段”。说白了就是 setState 导致 React.js 重新渲染组件并且把组件的变化应用到 DOM 元素上的过程,这是一个组件的变化过程。而 React.js 也提供了一系列的生命周期函数可以让我们在这个组件更新的过程执行一些操作。

    1. shouldComponentUpdate(nextProps, nextState):你可以通过这个方法控制组件是否重新渲染。如果返回 false 组件就不会重新渲染。这个生命周期在 React.js 性能优化上非常有用。
    2. componentWillReceiveProps(nextProps):组件从父组件接收到新的 props 之前调用。
    3. componentWillUpdate():组件开始重新渲染之前调用。
    4. componentDidUpdate():组件重新渲染并且把更改变更到真实的 DOM 以后调用。
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <title>React 生命周期</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </head>
    <body>
    <div id="root"></div>
    <script type="text/babel">
    class Clock extends React.Component {
      constructor (props) {
        super(props)
        this.state = {
          date: new Date()
        }
      }
      componentWillMount () {
        setTimeout(() => {
          this.setState({ date: new Date() })
        }, 1000)
      }
      componentWillReceiveProps () {
        console.log('componentWillReceiveProps');
      }
      shouldComponentUpdate () {
        console.log('shouldComponentUpdate');
        return true;
      }
      componentWillUpdate () {
        console.log('componentWillUpdate');
      }
      componentDidUpdate () {
        console.log('componentDidUpdate');
      }
      render () {
        const name = this.props.myName;
        return (
          <div>
            <h1>
              <p>{name},现在的时间是</p>
              {this.state.date.toLocaleTimeString()}
            </h1>
          </div>
        )
      }  
    }
    
    class Index extends React.Component {
      constructor () {
        super();
        this.state = {
          name: 'xu'
        }
      }
      componentWillMount () {
        setTimeout(() => {
          this.setState({ name: 'tongbao' })
        }, 2000)
      }  
      render () {
        return (
          <div>
            <Clock myName={this.state.name}/>
          </div>
        )
      }
    }
    ReactDOM.render(
      <Index />,
      document.getElementById('root')
    );
    </script>
    </body>
    </html>
  • 相关阅读:
    Laxcus集群操作系统的分布计算模型
    LAXCUS集群操作系统能不能防止DDOS攻击
    elasticsearch安装启动过程遇到的问题
    Centos7安装snort可视化IDS平台
    网络与信息安全 -国际学术会议和期刊目录
    包的概念、导入与可见性---Go
    Encrypted Traffic Analytics 加密流量分析功能
    商务谈判技巧
    东南大学《数字图像处理》课程作业 8
    东南大学《数字图像处理》课程作业 7
  • 原文地址:https://www.cnblogs.com/xutongbao/p/9924779.html
Copyright © 2011-2022 走看看