node.js - 当我尝试在 useEffect() 中更新 isAdmin 时,无法对未安装的组件执行 React 状态更新
问题描述
当我尝试通过 auth get 请求获取管理员的数据时,在控制台中收到此警告。
无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。
我需要匹配 jwt 令牌并获取数据以验证此人是否被授权。这是我的代码
//admin private route
const AdminRoute = ({ component: Component, render, ...rest }) => {
const [isAdmin, setIsAdmin] = React.useState(false);
React.useEffect(() => {
axios.defaults.headers.common["x-auth"] = localStorage.getItem(
"admintoken"
);
axios
.get("http://localhost:4000/api/adminauth")
.then(res => {
console.log(res.data);
setIsAdmin(true);
})
.catch(err => {
console.log(err);
setIsAdmin(false);
});
}, []);
return (
<Route
{...rest}
render={props => {
if (isAdmin === false) return <Redirect to="/" />;
return Component ? <Component {...props} /> : render(props);
}}
/>
);
};
解决方案
推荐阅读
- javascript - d3.js 错误:
属性 d:预期数字,“MNaN,360LNaN,43.9…” - python - 如何读取名称如 (1,1) 的 .hdf5 文件?
- flutter - 带有对齐对齐的 Flutter Wrap 小部件
- python - Kivy GridLayout scaling issues - Android vs PC - 16:9 and 19:5:9 vs 4:3(1920x1080 and 1440x3120 vs 800x600)
- python-3.x - 子矩阵右对角线 - Python
- firebase - 使用云功能部署到 Firebase 托管后,滚动插件上的动画在 Nuxt 版本 2 中不起作用
- java - RSelenium:为什么我不能向这个(Java?)登录字段发送密码?
- java - cucumber.runtime.CucumberException:没有找到后端。请确保您的 CLASSPATH 上有一个后端模块
- java - 如何从uri显示PDF)?
- excel - 如何将类模块类型的一维数组打印到 Excel VBA 中的范围?