• React(17.0版本)生命周期概述


    React17版本的生命周期概述。

    挂载

    示例代码在下方。

    当组件实例被创建并插入DOM的时候,其生命周期被调用顺序如下:

    1. constructor(props) - 初始化state和为事件处理函数绑定实例;
    2. static getDerivedStateFromProps(props, state) - 当state的值在任何时候都取决于props时使用,返回一个对象来更新state,返回null则不更新;
    3. render() - 渲染React组件;
    4. componentDidMount() - 组件挂载后调用,一个生命周期内仅一次;
      25c6aad22567e8309665ac3318ff93c2.jpg

    更新

    当组件的props或state发生变化时会触发更新。组件更新的生命周期顺序如下:

    1. static getDerivedStateFromProps(props, state);
    2. shouldComponentUpdate(nextProps, nextState) - 根据更新后的state或props判断是否重新渲染DOM,返回值为布尔值,常用来性能优化;
    3. render();
    4. getSnapshotBeforeUpdate(prevProps, prevState) - 是的组件能在发生改变之前从DOM中捕获一些信息(如滚动位置),返回值作为componentDidUpdate的第三个参数;
    5. componentDidUpdate(prevProps, prevState, snapshot) - state或props更新后调用
      33ae2b2a3ebfd7560d78a33f7686251d.jpg

    卸载

    • componentWillUnmount() - 组件销毁或卸载时调用;
      9fb18e381ab8e8204fcdd955ebaca1bd.jpg

    错误处理

    • static getDerivedStateFromError(callback) - 后代组件跑出错误时调用,并返回一个值以更新state;
    • componentDidCatch(error, info) - 后代组件抛出错误后调用,参数info包含有关组件错误的栈信息;

    其它

    • setState();
    • forceUpdate(callback) - 组件强制更新,会跳过shouldComponentUpdate;

    示例

    import * as React from "react";

    export class Test extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
    count: 1
    };
    console.log("1. constructor");
    }
    static getDerivedStateFromProps(props, state) {
    console.log("2. getDerivedStateFromProps");
    return {
    count: props.count
    };
    }
    componentDidMount() {
    console.log("3. componentDidMount");
    }
    shouldComponentUpdate() {
    console.log("4. shouldComponentUpdate");
    return true;
    }
    getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("5. getSnapshotBeforeUpdate");
    return null;
    }
    componentDidUpdate(props, state, snapshot) {
    console.log("6. componentDidUpdate");
    console.log("snapshot:", snapshot);
    }
    componentWillUnmount() {
    console.log("7. componentWillUnmount");
    }
    render() {
    console.log("0. render");
    const { count } = this.state;
    return (
    <ul>
    <li>state: {count}</li>
    <li>props: {count}</li>
    </ul>
    );
    }
    }
     

    完整周期:
    8ae37f7af5eb77ec7627ec5a3220286e.jpg

    参考

  • 相关阅读:
    让pv3d(papervision3D)支持单帧前进、后退(nextFrame)。
    4399 威武三国 网页游戏破解。
    策划进化史一 (2013-12-21)
    Java的一个高性能快速深拷贝方法。Cloneable?
    as3commons-bytecode 获取所有类的一个BUG
    MYSQL 大文件无法导入的问题。
    诡异的 未处理的IOErrorEvent 2035
    一个用微软官方的OpenXml读写Excel 目前网上不太普及的方法。
    如何在高并发环境下设计出无锁的数据库操作(Java版本)
    达洛克战记3 即将开服! What's New!
  • 原文地址:https://www.cnblogs.com/plBlog/p/14428928.html
Copyright © 2020-2023  润新知