React.Component class 构造函数在没有 console.log 的情况下运行一次?

React.Component class constructor runs once without console.log?

这个 React.Component class 构造函数在一个实例中似乎是 运行 2 次,以一种奇怪的方式。

显然:

  1. 计数器增加 0 -> 1 没有 console.log 输出
  2. 计数器增加 1 -> 2 with a console.log output

这是真的吗?为什么控制台显示 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 class 的行为符合预期:

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

发生这种情况是因为您正在使用 StrictMode:

... This is done by intentionally double-invoking the following functions:

Class component: constructor ...

模式调用了constructor两次,React也静默了日志:

Starting with React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions. ...

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