首页 > 解决方案 > 当我尝试在 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);
      }}
    />
  );
};

标签: node.jsreactjs

解决方案


推荐阅读