我正在嘗試將 404 頁面重定向到 Nextjs 中的主頁,但由于其中的一條規則,next.config.js它不起作用。每隔一個 404 重定向到主頁,但/blog/路由下的任何內容都會轉到默認的 Nextjs 錯誤頁面。
示例:
/category-1/post1重定向到/blog/category-1/post1,如果它不存在,它會呈現 404 頁面,但不會重定向到主頁。
這是我的_error.js檔案和404.js:
import { useEffect } from "react";
import { useRouter } from "next/router";
// export default function Custom404() ->in 404.js<-
export default function _error() {
const router = useRouter();
useEffect(() => {
router.push("/");
}, []);
return null;
}
和我的next.config.js檔案:
module.exports = {
reactStrictMode: true,
async redirects() {
return [
...oldBlogRedirectRules(),
]
}
// List of old categories
const blogCategoryUrlList = [
"category-1",
"category-2",
]
// Redirect old category and posts to /blog/[category]/[slug]
function oldBlogRedirectRules() {
return blogCategoryUrlList.map((url) => {
return {
source: `/${url}/:slug*`,
destination: `/blog/${url}/:slug*`,
permanent: true,
};
});
}
還有代碼在/blog/[category]/[slug].js
export default function Blog({ post }) {
const router = useRouter();
if (
!router.isFallback &&
...otherConditions
) {
return <ErrorPage statusCode={404} />;
}
return (
<>
{router.isFallback ? (
<h1>Loading...</h1>
) : (
...whatever
</>
);
}
uj5u.com熱心網友回復:
更新:@hungdoansy 在評論中回答
我印象深刻,因為我已經做出了更改,_error.js我不需要進行任何進一步的更改。
要解決此問題,只需從檔案中匯入函式404.js:
import Custom404 from 'pages/404.js';
export default function Blog({ post }) {
const router = useRouter();
if (
!router.isFallback &&
...otherConditions
) {
return <Custom404 />;
}
return (
<>
{router.isFallback ? (
<h1>Loading...</h1>
) : (
...whatever
</>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463563.html
