将所有`*`重定向到nextjs中的特定路径

问题描述 投票:0回答:2

我有一个登陆页面

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;
javascript reactjs next.js
2个回答
5
投票

不幸的是,nextJs 似乎没有正确的方法来处理 nextConfig 中的这种重定向,但是如果你想将任何 404 页面重定向到主页,你可以做的是:

  1. pages中创建自定义404页面,请注意,您的页面必须命名为404
  2. 将此代码段添加到 404 文件中。

import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Custom404() {
  const router = useRouter()

  useEffect(() => {
    router.replace('/')
  })

  return null
}

任何未找到的路线都应重定向到主页。 请参阅 github 上的讨论

编辑: 最后一件事,如果你想在用户访问某个路由时处理某种逻辑并在失败时重定向,你可以使用 getServerSideProps:

来实现
  1. 在渲染页面之前要在页面中处理某种逻辑的地方添加异步函数 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

这只是一个示例,但您已经明白了,如果您想了解更多信息,请阅读此处的文档


0
投票
{
   source: '/:path*',
   destination: '{SOME_URL}/:path*',
}
© www.soinside.com 2019 - 2024. All rights reserved.