Console.log在React.js的构造函数和渲染函数中两次打印值

问题描述

为什么console.log在构造函数和渲染函数中两次打印值?

在这里

class App extends React.Component {
  constructor(props) {
    console.log('Constructor');
    super(props)

    this.state = {
      counter: 0
    }
  }
render() {
    console.log('render');
    return (
      <div style={{ fontSize: '45px',fontWeight: 'bold' }}>
        Counter: {this.state.counter}
      </div>
    )
  }
}

解决方法

这是由于React.StrictMode引起的。 React.StrictMode是一个包装程序,可帮助为异步渲染准备应用程序。

您可以在此处了解更多信息! https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/