useEffect 在 React v18 中被调用两次

Anu*_*pta 10 javascript console frontend reactjs use-effect

我创建了一个全新的反应应用程序来自己测试这个,因为我的一个朋友面临这个问题。App.js 代码 ->

function App() {

  useEffect(() => {
    console.log('on init gets called');
  }, []);

  return (
    <>
      Hello my first react app      
    </>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

应用程序中不存在其他组件。以下是index.js代码->

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
Run Code Online (Sandbox Code Playgroud)

当我们第一次加载应用程序时,useEffect 中存在的 console.log 会打印两次。我希望它只打印一次。

Anu*_*pta 2

对我有用的调整 -> 删除了严格的反应模式,它可以正常工作。不确定是否有其他解决方案或为什么会发生这种情况。

  • const isMounted = useRef(); useEffect(() =&gt; { if (!isMounted.current) return; isMounted.current = true; // ...其余代码放在这里... },[]) (3认同)