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

标签 javascript reactjs next.js

我有一个着陆页 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 页面重定向到主页,你可以做的是:

  1. 页面内创建自定义 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
}

这样,任何未找到的路由都应该重定向到主页。 See this discussion on 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

这只是一个例子,但您已经明白了,如果您想了解更多信息,read the docs here

关于javascript - 将所有 `*` 重定向到 nextjs 中的特定路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71769431/

相关文章:

javascript - 单击按钮删除div

css - 如何在手机屏幕中设置maxWidth?

javascript - 如何使用 nextJs 和 next-i18next 像 URL 别名一样本地化路由?

Next.js 中每页的 CSS 拆分

next.js - 如何在nextjs的this.props中获取历史和匹配?

javascript - Materialize CSS 所有选项卡在彼此下面聚集在一起,但刷新后工作正常

javascript - 复制右键单击灯箱操作,就像在 github.com 上一样

javascript - 返回标准 SQL/BigQuery 结构并创建两列的 JS UDF

javascript - ReactJS OnKeyPress 触发按钮按下

reactjs - 在 useEffect 中 react 钩子(Hook) Prop