我正在开发一个带有身份验证的 Next.js 项目,并将一些 URL 作为字符串放入一个名为 protectedRoutes 的数组中,因此人们在登录之前访问这些 URL 时会被重定向。
const protectedRoutes = ["/home", "/profile", etc.];
我还有一些帖子要显示在我的项目中,每个帖子都有自己的页面。 每个帖子都有一个存储在 firebase 中的唯一 ID,我已经在 Next.js 中设置了路由器查询。
假设我有一个 post.id == "BjPDBvsWIsa11l6JxFOAgzR3mnG3" 所以它的 URL 是 /post/BjPDBvsWIsa11l6JxFOAgzR3mnG3.
我的问题是,如何将每个帖子的 URL 存储到 protectedRoutes 数组中?有什么办法可以用 Regex 做到这一点吗?
非常感谢。
const postURL = new RegExp("/post/")
const protectedRoutes = ["/home", "/profile", postURL];
不工作。
编辑 29/3:
我也希望避免以下情况:
const postID = getPostID() // function that fetches post IDs from firebase
postID.forEach((id) => {
protectedRoutes.push(`/post/${id}`);
});
所以为了避免在帖子数量增加时制作一个长数组,这会减慢搜索速度。
编辑 30/3:
下面显示了包含 protectedRoutes 的文件和处理重定向的组件。
在我的 _app.js 中,
import PrivateRoute from "@/components/PrivateRoute";
import { AuthProvider } from "@/contexts/AuthContext";
import "@/styles/globals.css";
export default function App({ Component, pageProps }) {
const protectedRoutes = ["/home", "/profile"];
const publicRoutes = [
"/",
"/sign-in",
"/sign-in/phone",
"/sign-up",
"/reset-password",
];
return (
<AuthProvider>
<PrivateRoute
protectedRoutes={protectedRoutes}
publicRoutes={publicRoutes}
>
<Component {...pageProps} />
</PrivateRoute>
</AuthProvider>
);
}
在我的 PrivateRoute.jsx 中,
import { useEffect } from "react";
import { useRouter } from "next/router";
import { useAuth } from "@/contexts/AuthContext";
import FullPageLoader from "./FullPageLoader";
export default function PrivateRoute({
protectedRoutes,
publicRoutes,
children,
}) {
const router = useRouter();
const { currentUser, loading } = useAuth();
const pathIsProtected = protectedRoutes.indexOf(router.pathname) !== -1;
const pathIsPublic = publicRoutes.indexOf(router.pathname) !== -1;
useEffect(() => {
if (!loading && !currentUser && pathIsProtected) {
router.push("/sign-in");
}
if (!loading && currentUser && pathIsPublic) {
router.push("/home");
}
}, [currentUser, loading, pathIsProtected, pathIsPublic]);
if ((loading || !currentUser) && pathIsProtected) {
return <FullPageLoader />;
}
if ((loading || currentUser) && pathIsPublic) {
return <FullPageLoader />;
}
return children;
}
测试跟随代码,
const url1 = '/post/dadsa'
const url2 = '/post/sdadasdas/dadsa'
const url3 = '/postsdadasdas/dadsa'
const getRealPath = (url)=> {
return '/' + url.split('/').filter(v=>v!=='')[0]
}
console.log(getRealPath(url1))
console.log(getRealPath(url2))
console.log(getRealPath(url3))
编辑你的_app.js,
const protectedRoutes = ["/home", "/profile", "/post"];
编辑您的 PrivateRoute.jsx,
+ const getRealPath = (url) => '/' + url.split('/').filter(v=>v!=='')[0]
- const pathIsProtected = protectedRoutes.indexOf(router.pathname) !== -1;
+ const pathIsProtected = protectedRoutes.indexOf(getRealPath(router.pathname)) !== -1;