反应最大更新深度超出错误

时间:2021-05-17 06:40:51

标签: reactjs cookies local-storage

如果用户手动清除 localstorage 或 cookie 令牌,我想重定向到登录。如果我根据 Cookie 'undefined' 设置条件,我会收到错误:超出最大更新深度。React 限制嵌套更新的数量以防止无限循环。

//components
import routes from "./route_config";
import { accessTokenHelper } from "../helper/token"

const authed = () => localStorage.hasOwnProperty("TOKEN");
const authToken = accessTokenHelper.get();

const authPath = "/login";

const Routes = () => (
  <Router>
    <Suspense fallback={"Loading...."}>
      <Switch>
        {routes.map((route, i) => (
          <Route
            key={route.key || i}
            path={route.path}
            exact={route.exact}
            render={(props) => {
              if (route.authentication && route.path !== authPath) {
                if (authToken) {
                  return <route.component {...props} routes={route.routes} />;
                }
                if (!authToken) return <Redirect to="/login" />;
              }
              if (!route.authentication) {
                if (route.path === authPath) {
                  if (authed()) return <Redirect to="/" />;
                  if (!authed()) return <route.component {...props} />;
                } else if (route.default) {
                  if (authed()) return <Redirect to="/" />;
                  if (!authed()) return <Redirect to="/login" />;
                } else {
                  return <route.component {...props} />;
                }
              }
            }}
          />
        ))}
      </Switch>
    </Suspense>
  </Router>
);

export default Routes;

0 个答案:

没有答案