【问题标题】:How to get dynamic page's id如何获取动态页面的id
【发布时间】:2022-01-13 09:02:37
【问题描述】:

我有一个 HOC,如果没有令牌,它会将用户重定向到登录。我想要实现的是在重定向之前存储用户打算访问的网址并将他推回该页面。但问题是在 HOC 中我只得到 /product/[id] 而不是 /product/1

withAuth.ts:

import { TokenService } from '@/api/tokenService';
import { useRouter } from 'next/router';
import React from 'react';

type TWithAuth = {
    WrappedComponent: JSX.Element;
};

export function withAuth<T extends TWithAuth = TWithAuth>(
    WrappedComponent: React.ComponentType<T>,
): React.ComponentType<T> {
    const InnerComponent = (props: T) => {
        if (typeof window !== 'undefined') {
            const Router = useRouter();
            console.log(Router);
            const accessToken = TokenService.getAccessToken();

        if (!accessToken) {
            Router.replace('/auth/login');
            return null;
        }

        return <WrappedComponent {...props} />;
    }

    return null;
};

InnerComponent.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name}`;

return InnerComponent;
}

【问题讨论】:

  • 你从哪里得到/product/[id]?您可以在客户端使用router.asPath 来检索实际路径:/product/1
  • 我在 userRouter() 调用的结果中到处都是/product/[id]

标签: javascript reactjs react-hooks next.js


【解决方案1】:

我假设您没有使用服务器端渲染 (getServerSideProps)。 然后,您需要在客户端(浏览器)的请求之间保持状态

这些是步骤:

  • 当用户登陆页面但未登录时,将原始页面请求保存到 cookie 或本地存储中。
  • 重定向到登录
  • 登录用户。
  • 当用户登录成功后,检查cookie,
  • 如果有cookie(或本地存储),取数据(原始URL)
  • 删除 cookie
  • 重定向到原始页面。

【讨论】:

  • 不,我不是。实际上,我阅读了您关于保护路线的帖子,它非常好。但我无法访问路线的动态部分。 (在这种情况下我没有 SSR)
【解决方案2】:

您在 if 语句中调用 useRouter 挂钩,这违反了挂钩的第一条规则。

还有,

试试:

export function withAuth<T extends TWithAuth = TWithAuth>(
    WrappedComponent: React.ComponentType<T>,
): React.ComponentType<T> {
    const InnerComponent = (props: T) => {
        const Router = useRouter();
        useEffect(()=> console.log(Router), []);
        const accessToken = TokenService.getAccessToken(); // is it async? If so, maybe it should be wrapped inside useEffect

        if (!accessToken) {
            Router.replace('/auth/login');
            // no need to return null, you are already redirecting
        }

        return <WrappedComponent {...props} />;
    }
    return null;
};

【讨论】:

  • 不,查询参数为空
  • 有没有办法使用中间件做到这一点?
猜你喜欢
  • 1970-01-01
  • 2011-12-04
  • 2012-03-29
  • 2013-04-25
  • 2016-03-22
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多