【问题标题】:React.Component class constructor runs once without console.log?React.Component 类构造函数在没有 console.log 的情况下运行一次?
【发布时间】:2021-09-18 23:01:42
【问题描述】:

这个 React.Component 类构造函数似乎以一种奇怪的方式为一个实例运行了 2 次。

显然:

  1. 计数器递增0 -> 1 没有 console.log 输出
  2. 计数器增加 1 -> 2 输出控制台日志

这是真的吗?为什么控制台显示2 而不是1?

import React from 'react';

var instanceCount = 0;
console.log('root:', instanceCount);

class App extends React.Component {

    constructor(props) {
        super(props);
        console.log('before change:', instanceCount);
        instanceCount++;
        console.log('after change:', instanceCount);
    }

    render() {
        return (
            <>test</>
        );
    }
}

export default App;

// console output:
//   root: 0
//   before change: 1
//   after change: 2

相比之下,“正常”的 javascript 类的行为符合预期:

var instanceCount = 0;
class SomeClass {
    constructor(props) {
        console.log('before change:', instanceCount);
        instanceCount++;
        console.log('after change:', instanceCount);
    }
}
var instance = new SomeClass();

// console output:
//   before change: 0
//   after change: 1

【问题讨论】:

  • 尝试将var instanceCount = 0; console.log('root:', instanceCount); 放在class App extends React.Component { 中,但在render() 之前

标签: reactjs constructor


【解决方案1】:

这是因为您使用的是StrictMode:

... 这是通过有意双重调用以下函数来完成的:

类组件:constructor ...

该模式调用constructor 两次,React 也将日志静音:

从 React 17 开始,React 自动修改控制台 像console.log() 这样的方法在第二次调用中使日志静音 生命周期函数。 ...

// Remove StrictMode
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2017-03-27
    • 2012-08-17
    相关资源
    最近更新 更多