#独家
为什么 React 18 里的类组件在严格模式下会执行的模拟渲染 constructor 会先于首次渲染的 componentDidMount 执行?

2023-07-14 0 1,577

react 18 里的类组件在严格模式下会执行一次模拟渲染, 在类组件的生命周期里表现如下
first.constructor -> second.constructor -> first.componentDidMount -> first.componentWillUnmount -> second.componentDidMount

一个比较简单的例子就是,复现链接(https://playcode.io/1531037)

组件卸载的时候改的是同一个对象,导致第一次卸载时把第二次在 constructor 里初始化的对象给重置了

import React from 'react';

export class App extends React.Component {
    constructor(props) {
        super(props);
        console.log(0);
    }

    componentDidMount() {
        console.log(1);
    }

    componentWillUnmount() {
        console.log(2);
    }

    render() {
        return <div>1</div>;
    }
}

上面的输出是

00121

这个问题会导致在第二次渲染 constructor 执行时里面初始化的内容被第一次渲染卸载时重置,导致第二次渲染时要用到初始化内容时报错,如下(复现 https://playcode.io/1531064

import React from 'react';

function A() {};

export class App extends React.Component {
    ob;

    constructor(props) {
        super(props);
        console.log(0);
        this.ob = new A();
    }

    componentDidMount() {
        console.log(1);
        console.log(this.ob);
        //all operations on ob will report an error
    }

    componentWillUnmount() {
        console.log(2);
        this.ob = null;
    }

    render() {
        return <div>1</div>;
    }
}

目前的修补方法是把初始化改到 componentDidMount 里面,但是这个问题的原因是什么呢?为什么两次渲染改到了同一个对象?

你可以把对象的初始化放在 componentDidMount 里,或者用 React 的新的生命周期方法 getDerivedStateFromProps 或者 getSnapshotBeforeUpdate。这两个方法在每次渲染前都会被调用回复

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 为什么 React 18 里的类组件在严格模式下会执行的模拟渲染 constructor 会先于首次渲染的 componentDidMount 执行? https://www.jkxiazai.com/2036.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务