React 入门小册(五) 生命周期

React生命周期是指组件在不同阶段中的方法调用顺序,它可以帮助我们更好地管理组件的状态和行为。
下文将介绍React16的生命周期方法,并逐一分析其作用。

组件实例化时期

constructor()

创建组件实例时首先调用的构造函数,在 ES6 中定义的 class 里第一个被调用,并且不能省略。通常用来初始化组件的状态值以及绑定成员函数的this对象。

constructor(props) {
    
    
    super(props);
    this.state = {
    
     count: 1 };
    this.handleClick = this.handleClick.bind(this);
}
componentWillMount()

组件渲染之前触发,只会在挂载前调用一次,此时还未访问到 DOM 元素和存在生命周期中。通常在这个方法中去加载一些异步数据或者资源。

render()

render() 是类组件必须实现的方法,也是最重要的方法之一,负责返回 JSX,被称作纯函数,即每次调用输出结果相同,不应产生副作用。

componentDidMount()

组件渲染完成后调用,可以使用refs获取到对应的真实DOM节点并进行必要的操作(例如依赖 jquery 的 UI 组件的根元素重新排版布局等),当然也可以调用 setState 改变组件状态,如果需要发起网络请求的话,可以使用 componentDidMount() 方法,因为大多数 HTTP 请求都使用异步 API,这种写法可以避免服务器高并发导致浏览器阻塞。

组件存在更新时期

componentWillReceiveProps(nextProps)

组件接收到 props 时被触发,内部可以通过比较 nextProps 和 this.props 达到条件渲染。

shouldComponentUpdate(nextProps, nextState)

判断组件的 this.props 和 this.state 是否与 nextProps 和 nextState 不相同,若都不相同则返回 true 并触发 render 方法重新渲染,否则不渲染。

componentWillUpdate(nextProps, nextState)

shouldComponentUpdate 返回 true 或调用 forceUpdate() 后,会触发该方法,可在方法内对更新的 props 和 state 进行比对,根据实际场景作出更新。

render()

类似上面的“组件实例化时期”中的描述。

componentDidUpdate(prevProps, prevState)

组件完成更新后调用,可执行 DOM 操作等。在 componentDIdUpate 函数中可以获取两个参数:prevProps, prevState 表示改变之前的props和state值。

组件消亡时期

componentWillUnmount()

组件被销毁时会调用的一个函数,若当前组件正在监听某些事件或正在轮询一段时间内发生数量变化的数据,需要在 unmount 时候释放掉已占用的相关资源,以免浪费散落在页面各处没有清理干净的痕迹而导致内存泄漏。

使用方法示例
import React, {
    
     Component } from 'react';

class App extends Component {
    
    
    constructor(props) {
    
    
        super(props);
        this.state = {
    
    
            name: 'Alice'
        };
    }

    componentDidMount() {
    
    
        document.title = `Welcome ${
      
      this.state.name}`;
    }

    componentWillReceiveProps(nextProps) {
    
    
        if (nextProps.name !== this.state.name) {
    
    
            this.setState({
    
     name: nextProps.name });
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
    
    
        return nextState !== this.state;
    }

    componentDidUpdate(prevProps, prevState) {
    
    
        if (prevState.name !== this.state.name) {
    
    
            document.title = `Welcome ${
      
      this.state.name}`;
        }
    }

    componentWillUnmount() {
    
    
        console.log('Component will be unmounted.');
    }

    render() {
    
    
        return (
            <div>
                <h1>Hello, {
    
    this.state.name}!</h1>
                <button onClick={
    
    () => this.setState({
    
     name: 'Bob' })}>Change Name</button>
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

以上就是React生命周期的介绍及使用方法,随着React的不断更新

猜你喜欢

转载自blog.csdn.net/weixin_42657666/article/details/129566844