TDLR;
知道在next build && next export
没有 .js 应用程序 ()的静态导出中成功重新加载动态路由的最佳方法是getStaticPaths
什么?
当我使用 create-react-app 和 react-router 时,我必须在文件夹中添加以下.htaccess
文件,该/public
文件将被复制/粘贴到输出/build
文件夹中
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
它允许从任何路由重新加载的任何页面重定向到应用程序内的正确路由,而不是使用 404。
使用 Next.js,作为连接到外部 api 的静态站点,使用动态路由具有这种行为似乎有点复杂。这不是我可以生成的动态路线,getStaticPaths
因为我无法预测这些路径。
我的页面是一个测验,您可以在其中查看您的结果并根据需要分享它们。所以我有
/result
当我登录时,这是我的私人结果页面/result/[anyName]
将是公共结果的页面
在没有 403 或 404 的情况下,很难让页面重新加载正常工作。我尝试了很多东西,比如
- 在 .
RewriteRule ^result/(.*)$ /result [R=301,NC,L]
-> 没用 exportPathMap
在我的-> 中添加一个next.config.js
不起作用。
const moduleExports = {
reactStrictMode: true,
exportPathMap: () => ({
"/": { page: "/" },
"/result/arnaud": { page: "/result" },
}),
images: {
loader: "imgix",
path: "",
},
trailingSlash: true,
};
我最终做的是一个技巧:在index.js
我页面的根目录中,显示路径的那个/
:
const router = useRouter();
useEffect(() => {
if (router.asPath?.includes("result") && router.asPath?.split("/").length > 1) {
router.push(router.asPath);
}
}, [router.asPath]);
它实际上是在做这个把戏,但我不太喜欢这样。有了可靠的东西.htaccess
,我可以盲目地将粘贴从项目复制到项目,这要容易得多。
有更好的吗?