【发布时间】: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