【发布时间】: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;
-
你在用
<StrictMode>吗?如果是这样,这是预期的行为。在开发版本中,严格模式将模拟卸载和重新安装组件,因此您可以更轻松地捕获与不拆除效果相关的错误。 reactjs.org/docs/strict-mode.html#ensuring-reusable-state -
我同意@NicholasTower,也许你正在使用
<StrictMode>。 -
是的,我使用的是严格模式
标签: javascript reactjs