当前位置: 首页 > 知识库问答 >
问题:

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

傅朗
2023-07-13

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 里面,但是这个问题的原因是什么呢?为什么两次渲染改到了同一个对象?

共有1个答案

鲁浩言
2023-07-13

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

 类似资料:
  • 我的React组件渲染了两次。所以,我决定逐行调试,问题就在这里 做出反应。发展js 是因为严格的模式吗?我能禁用它吗?什么是严格模式?我需要它吗?

  • 我已经开始维护一个遗留的JSF应用程序。它使用myFaces 1.1。x和战斧1.1.6。我需要打印tag作为元素的第一个元素,否则IE会忽略它。 它将产生 如何强制元标记成为第一个元素?我尝试了纯HTML HEAD元素,但它也不起作用。 我需要 更新: 其中一些Java脚本和样式是由于以下标记而呈现的: 剩下的javascript来自 问题是我是否可以强制执行我给t:documentHead的内

  • react class组件在componentDidMount中调用初始化接口,有些时候会调用两次,通过断点发现顺序是componentDidMount->componentWillUnmount->componentDidMount,但不能稳定复现,调用的组件是页面的主入口,并非某个组件的子组件,请问有知道这个问题的么?

  • 我遇到了这个简单的React函数组件,它渲染四次,而我希望它最初渲染一次,执行useffect更新状态,然后再次渲染。相反,控制台发送4个日志输出,表示它渲染了4次。了解react功能组件的基本生命周期的原因和资源吗? https://codesandbox.io/s/solitary-tree-t120d?file=/src/App.js:149-191

  • 拥有如此简单的CRAapp: ./index.tsx: ./组件/主页。tsx: 我得到: 在控制台上。 为什么promise履行代码会被触发2次?我知道,对于React Strict模式,组件渲染了两次,但示例显示了一些不一致性-

  • 本文向大家介绍javascript表格的渲染组件,包括了javascript表格的渲染组件的使用技巧和注意事项,需要的朋友参考一下 表格的渲染组件,demo请点击http://lovewebgames.com/jsmodule/table.html,git源码请点击https://github.com/tianxiangbing/table 如上图所示,功能基本包括常用表格中遇到的分页、搜索、删除