简体   繁体   English

组件中的 Function 在 React js 中被调用两次

[英]Function in the component is getting called twice in react js

I am using useMemo react hook in the function component.我在 function 组件中使用useMemo反应挂钩。 I am not sure why the console log is getting twice printed.我不确定为什么控制台日志被打印两次。 Here below is my code:下面是我的代码:

import './App.css';
import react,{useState,useMemo} from 'react';

function App() {

  const [count,setCount] = useState(0);
  const [item,setItem] = useState(10);

  const multiCountMemo = useMemo(function multiCount() {
    console.log("to check if getting inside the function")  <---- this is getting printed twice by default on load app page.
    return count * 5
  },[count])


  return (
    <div className="App">
      <h1>useMemo Hook Usage</h1>

      <h2>Count : {count}</h2>
      
      <h2>Item : {item}</h2>

      <h2>{multiCountMemo}</h2>

      <button onClick={() => setCount(count + 1)}>Update Count</button>
      
      <button onClick={() => setItem(item * 10)}>Update Item</button>
    </div>
  );
}

export default App;

在此处输入图像描述

This is due to strict mode check the docs here .这是由于严格模式检查这里的文档。

useEffect in react version 18 causes the component to unmount and mount again after it mounts the first time. React 版本 18 中的 useEffect 导致组件在第一次安装后卸载并再次安装。 This is why the console.log is triggering twice这就是console.log触发两次的原因

note that this only happens in development mode and not production请注意,这只发生在开发模式而不是生产模式反应文档显示严格模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM