在 Next-JS 中,UseEffect() 运行两次。我听说你需要将一个空数组作为第二个参数来修复 React 中的这个问题。就我而言,在 Next-JS 中,这不起作用。(据我所知,Next-JS是基于React的)。
我找到了一种方法:在 next.config.js 中设置reactStrictMode: false。它有效,UserEffect 被调用一次。
但这种方法不适合我,因为。我需要使用 React 的严格模式。
_app.js:
import '../styles/globals.css';
import React, { useEffect, useState, useRef } from 'react';
function MyApp({ Component, pageProps }) {
if (typeof window !== "undefined") {
useEffect(() => {
console.log('Component Did Mount') //called twice :c
}, [])
return <Component {...pageProps} />
}
export default MyApp
Run Code Online (Sandbox Code Playgroud)