简体   繁体   English

反应组件中没有依赖关系的useEffect执行两次

[英]useEffect without dependencies in react component executes twice

Hello I have a problem with useEffect .您好,我对useEffect有疑问。 It is without dependencies because I want to execute this only once.它没有依赖关系,因为我只想执行一次。 I'm also using react router v6.我也在使用反应路由器 v6。 But the useEffect in Profiles.js component runs twice and I don't know how to fix it.但是Profiles.js组件中的useEffect运行了两次,我不知道如何修复它。 Below it is the App component which is the parent of Profile and the Profile component which is the problem.下面是作为 Profile 父级的 App 组件和问题所在的 Profile 组件。

App.js:应用程序.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: 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;

You most likely have <React.StrictMode/> enabled (Somewhere you are wrapping your application in <React.StrictMode/>).您很可能启用了<React.StrictMode/> (在某处您将应用程序包装在 <React.StrictMode/> 中)。 This behaviour will only occur on the development environment (meaning that on production useEffect will run only once).此行为只会在development环境中发生(意味着在生产环境中 useEffect 只会运行一次)。 If you do not want that behaviour on your development environment then remove the <React.StrictMode/> wrapper.如果您不希望在development环境中出现这种行为,请删除<React.StrictMode/>包装器。

You can read more about StrictMode here: https://reactjs.org/docs/strict-mode.html您可以在此处阅读有关StrictMode的更多信息: https://reactjs.org/docs/strict-mode.html

in development mode usseefect run twice beacuse of strictmode, bulid your project you can see it works as you perform.在开发模式下,由于严格模式,usseefect 运行两次,构建您的项目,您可以看到它在执行时工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM