浅析React生命周期之一:挂载阶段

栏目: IOS · Android · 发布时间: 7年前

内容简介:学习React有一个很重要的概念需要弄清楚,那就是React组件的生命周期,以及它跟 setState 所引起的 React生命周期钩子的调起情况。React 生命周期分为挂载阶段、更新阶段和卸载阶段。下面我将使用核心代码如下,简单输出各生命周期钩子的日志信息:浏览器输出日志如下,结果很简单明了:

学习React有一个很重要的概念需要弄清楚,那就是React组件的生命周期,以及它跟 setState 所引起的 React生命周期钩子的调起情况。React 生命周期分为挂载阶段、更新阶段和卸载阶段。下面我将使用 create-react-app 做一个简单的分析,React版本是 16.8.1

一、挂载阶段

1.1 组件初次挂载,依序执行以下方法。除了 render,其他3个函数只会执行一次。

  • constructor
  • componentWillMount
  • render
  • componentDidMount

核心代码如下,简单输出各生命周期钩子的日志信息:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count:0
    };
    console.log('constructor')
  }
  componentWillMount(){
    console.log('componentWillMount')
  }
  componentDidMount() {
    console.log('componentDidMount')
  }
  //WARNING! To be deprecated in React v17. Use componentDidUpdate instead.
  componentWillUpdate(nextProps, nextState) {
    console.log('componentWillUpdate')
  }
  componentDidUpdate(){
    console.log('componentDidUpdate')
  }
  componentWillReceiveProps(nextProps) {
    console.log('componentWillReceiveProps')
  }

  render() {
    console.log('render', this.state)
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
          <button onClick={this.handleClick}>click me</button>
        </header>
      </div>
    );
  }
}

export default App;
复制代码

浏览器输出日志如下,结果很简单明了:

浅析React生命周期之一:挂载阶段

1.2 接下来,要稍微搞一下事情了,在 componentWillMount 中setState更新状态会怎么样呢?

componentWillMount(){
    console.log('componentWillMount')
    this.setState({foo: 'bar'});
}
复制代码

浏览器输出日志如下,可以看到在 componentWillMount 中更新状态不会触发更新过程,但会新的状态会及时在 render 中体现:

浅析React生命周期之一:挂载阶段

在这里,我们需要注意到 setState 是异步的操作:

componentWillMount(){
   console.log('componentWillMount')
   console.log('componentWillMount before setState',this.state)
   this.setState({foo: 'bar'});
   console.log('componentWillMount after setState',this.state)
}
复制代码

浏览器输出日志如下,可以看到执行setState操作后,state 对象没有立即生效,而是到了 render 函数中才生效。

浅析React生命周期之一:挂载阶段

1.3 利用 setState 的回调,可以获知渲染完毕后的新的 state 内容,代码和日志信息如下:

componentWillMount(){
    console.log('componentWillMount')
    console.log('componentWillMount before setState',this.state)
    this.setState({foo: 'bar'},() => {
      console.log('componentWillMount after setState',this.state)
    });
}
复制代码
浅析React生命周期之一:挂载阶段

1.4 如果连续多次 setState,react 内部做了优化,不会触发多次更新。代码和日志信息如下:

componentWillMount(){
    console.log('componentWillMount')
    this.setState({foo: 'bar'});
    this.setState({foo: 'bar2'});
}
复制代码
浅析React生命周期之一:挂载阶段

1.5 如果需要获知当前最新的 state 内容,以计算下一个 state 内容,则需要使用函数传参形式的 setState,见下图。

可以在此看处 setState后于 console.log('do some calculate or other operation...') 执行,再次反映了 setState的异步执行机制。这里,透露了一个最佳实践建议,即:

在 setState 之前做好计算,最后再一次性 setState。这样,代码顺序就和执行顺序一致,出问题时才不会一脸懵逼。

浅析React生命周期之一:挂载阶段

1.6 然后是还没怎么提到的 componentDidMount

组件挂载完成后执行,可以在这里拉取服务器数据(当然,也可以在上面提到的 componentWillMount 中拉取远程数据)。也可以在这里添加对dom 的监听及其他对dom 的操作,还可以创建定时器。(相应的,需要在 componentDidMount 中销毁 dom 的监听和 timer,以免造成内存泄漏)


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具