我有一个着陆页 nextJs
应用程序,可以将所有 *
重定向到特定路线,就像我们在 react-router
中所做的那样我怎样才能在 nextJs
<BrowserRouter>
<Routes>
<Route path={ROUTES.ROOT} element={<Registry />} />
<Route path={ROUTES.ALL} element={<Navigate to={ROUTES.ROOT} />} />
</Routes>
</BrowserRouter>
export const ROUTES = {
ALL: '*',
ROOT: '/registry',
};
到目前为止我所做的是,我能够将特定路由重定向到特定路由,但无法将所有路由重定向到特定路由
const nextConfig = {
async redirects() {
return [
{
source: '/path', // not able to "*" the route
destination: '/registry', // Matched parameters can be used in the destination
permanent: false,
},
];
},
};
module.exports = nextConfig;
最佳答案
不幸的是,nextJs 似乎没有正确的方法来处理 nextConfig 中的这种重定向,但是如果你想将任何 404 页面重定向到主页,你可以做的是:
- 在页面内创建自定义 404 页面,请注意,您的页面必须命名为404
- 将此代码段添加到 404 文件中。
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Custom404() {
const router = useRouter()
useEffect(() => {
router.replace('/')
})
return null
}
这样,任何未找到的路由都应该重定向到主页。 See this discussion on github
编辑: 最后一件事,如果您想在用户访问某个路由时处理某种逻辑并在失败时重定向,您可以使用 getServerSideProps 来实现:
- 在页面中添加异步函数 getServerSideProps,以便在渲染页面之前处理某种逻辑:
// Page where you want to handle the logic
// data is the props that comes from getServerSideProps
function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps() {
// fetch some data from external API
const res = await fetch(`https://someapi/fetchData`)
const data = await res.json()
if(!data) {
// Here we redirect the user to home if get some error at the API
return {
redirect: {
destination: '/',
permanent: false
}
}
}
// Otherwise pass the data to Page as props
return { props: { data } }
}
export default Page
这只是一个例子,但您已经明白了,如果您想了解更多信息,read the docs here
关于javascript - 将所有 `*` 重定向到 nextjs 中的特定路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71769431/