【问题标题】:Function in the component is getting called twice in react js组件中的函数在 react js 中被调用两次
【发布时间】:2022-12-01 01:03:33
【问题描述】:

我在用使用备忘录功能组件中的反应钩子。 我不确定为什么控制台日志被打印两次。下面是我的代码:

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;

【问题讨论】:

标签: javascript reactjs react-hooks


【解决方案1】:

这是由于严格模式检查文档here

React 版本 18 中的 useEffect 导致组件在第一次安装后卸载并再次安装。 这就是 console.log 触发两次的原因

请注意,这只发生在开发模式而不是生产模式

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多