当我尝试在useEffect()中更新isAdmin时,无法在已卸载的组件上执行React状态更新

时间:2020-03-24 10:12:04

标签: node.js reactjs

当我尝试通过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);
      }}
    />
  );
};

0 个答案:

没有答案