【问题标题】:useEffect without dependencies in react component executes twice反应组件中没有依赖关系的useEffect执行两次
【发布时间】:2022-08-14 01:13:40
【问题描述】:

您好,我对useEffect 有疑问。它没有依赖关系,因为我只想执行一次。我也在使用反应路由器 v6。但是Profiles.js 组件中的useEffect 运行了两次,我不知道如何修复它。下面是作为 Profile 父级的 App 组件和问题所在的 Profile 组件。

应用程序.js:

function App() {
return (
    <div>
        <Navbar />
        <Routes>
            <Route
                element={<Navigate replace={true} to={\"/welcome\"} />}
                path=\"/\"
            />
            <Route element={<Profiles />} path={`/profiles`} exact />
            <Route element={<LandingPage />} path={\"/welcome\"} />
            <Route element={<Main />} path={\"/main\"} />
            <Route element={<MyProfile />} path={\"/myprofile\"} />
        </Routes>
    </div>
);
}

export default App;

Profiles.js:

const Profiles = (props) => {
const [profiles, setProfiles] = useState([]);

useEffect(() => {
    const fetchProfiles = async () => {
        console.log(\"profiles\");
        // const snapshot = await get(ref(database, `users/`));
        // if (snapshot.exists()) {
        //     const response = snapshot.val();
        //     for (const uid in response) {
        //         if (uid !== user.uid) {
        //             setProfiles((prevState) => {
        //                 return [response[uid], ...prevState];
        //             });
        //         }
        //     }
        // }
    };
}, []);
return (
    <div>
        <ProfileRecommendation />
    </div>
);
};

export default Profiles;
  • 你在用&lt;StrictMode&gt;吗?如果是这样,这是预期的行为。在开发版本中,严格模式将模拟卸载和重新安装组件,因此您可以更轻松地捕获与不拆除效果相关的错误。 reactjs.org/docs/strict-mode.html#ensuring-reusable-state
  • 我同意@NicholasTower,也许你正在使用&lt;StrictMode&gt;。
  • 是的,我使用的是严格模式

标签: javascript reactjs


【解决方案1】:

您很可能启用了&lt;React.StrictMode/&gt;(在某处您将应用程序包装在 <React.StrictMode/> 中)。这种行为只会在development 环境中发生(这意味着在生产环境中 useEffect 只会运行一次)。如果您不希望在 development 环境中出现这种行为,请删除 &lt;React.StrictMode/&gt; 包装器。

你可以在这里阅读更多关于StrictMode的信息:https://reactjs.org/docs/strict-mode.html

【讨论】:

    【解决方案2】:

    在开发模式下 useeffect 由于 strictmode 运行两次,构建你的项目你可以看到它在你执行时工作。

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 2021-07-17
      • 2022-06-25
      • 1970-01-01
      • 2021-01-16
      • 2020-01-23
      • 2016-05-12
      • 1970-01-01
      • 2011-04-14
      相关资源
      最近更新 更多