美文网首页
react为什么会打印两遍console.log?

react为什么会打印两遍console.log?

作者: 刘其瑞 | 来源:发表于2024-03-13 17:53 被阅读0次

一个简单的组件初始化时执行两遍,点击事件后又触发两遍。

import { useEffect, useState } from 'react';

function App () {
  const [count, setCount] = useState(0);

  console.log("执行测试")

  const handleClick = () => {
    setCount(3)
  }

  return <div onClick={handleClick}>{count}</div>
}

export default App;

改成类写法试一下,发现constructor和render同样都会执行两遍

import React from 'react';
class App extends React.Component {
  constructor(props) {
    super();
    this.props = props;
    console.log("类组件的构造函数被调用了");
  }

  render () {
    console.log("类组件的render被调用了");
    return (
      <div>
        <h5 >我是类组件</h5>
      </div>
    );
  }
}

这是因为React.StrictMode,这只发生在开发中,它们不会影响生产构建。如果删除React.StrictMode,将只打印一次。

index.js

有关更多详细信息,请查看react repo上的此线程:

https://github.com/facebook/react/issues/15074

在进一步阅读时,我也在React文档中找到了这个:https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

相关文章

网友评论

      本文标题:react为什么会打印两遍console.log?

      本文链接:https://www.haomeiwen.com/subject/yelizdtx.html