对严格模式的更改反应版本 18导致我的代码渲染两次,这会导致错误axios中止控制器,但我不知道如何清除error应用程序渲染两次后从浏览器控制台。
请注意:我正在开发一个注册/登录应用程序,即使在我成功登录后,React带我回到登录页面,因为axios error
useEffect(() => {
let isMounted = true;
// used by axios to cancel request
const controller = new AbortController();
const getGoals = async () => {
try {
const response = await goalPrivate.get("/goals", {
// option to cancel request
signal: controller.signal
})
console.log(response?.data);
// set goals state when component mounts
isMounted && setGoals(response?.data);
} catch (error) {
console.log(error.message);
// when refreshToken expires
navigate("/login", { state: { from: location }, replace: true });
}
}
getGoals();
// cleanup function
return () => {
// don't set state if component unmounts
isMounted = false;
// cancel request if component unmounts
controller.abort();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
React StrictMode 调用所有 Effects 两次,以确保它们的清理/卸载处理程序按预期工作。您可能需要相应地更改效果,即使它们具有空的依赖项列表并且通常不会在站点关闭之前卸载。
请注意,这只发生在严格+开发模式下。在生产构建中,效果只会在其依赖项发生变化时被调用一次。
有关更多上下文,请参阅https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)