【问题标题】:Next.js overlaps static route with dynamic routeNext.js 将静态路由与动态路由重叠
【发布时间】:2022-01-04 06:47:36
【问题描述】:

我正在使用 Next.JS 应用程序路由系统。

我创建了一个动态路由,其结构类似于pages/[country]/[language]/index.js

还有一个结构为pages/cz/cz/index.js的静态路由。

问题出现然后我在静态页面上并尝试通过Link 组件导航以访问静态路由内容在我的情况下应该转到主页并重新加载同一页面,而不是呈现动态路由内容。

在我的例子中,链接只是简单的导航到主页<Link to="/"> 的两条路线。 但问题可能在于如何为预定义和动态路由设置 index.js 文件。

cz/cz/index.js

export { default } from '../../../components/HomePage/';

const { getStaticProps } = createRoute({
  path: '/',
  locale: 'cs',
});

export { getStaticProps };

[国家]/[语言]/index.js

export { default } from '../../../components/HomePage/v2';

const { getStaticPaths, getStaticProps } = createRoute({
  path: '/',
  exclude: ['cs'],
  otherLocales: ['cs'],
});

export { getStaticPaths, getStaticProps };

创建路线

export default function createRoute({
  path,
  otherLocales,
  getPathParams,
  locale,
} = {}) {
  const locales = _.without(include, ...exclude);
  return {
    getStaticPaths: createGetStaticPaths({
      locales,
      getPathParams,
    }),
    getStaticProps: createGetStaticProps({
      path,
      locale,
      locales,
      otherLocales,
    }),
  };
}

页面结构

那么为什么[country]/[language]/index.js 会覆盖cz/cz/index.js

那么在 nextJS 路由中是否有任何东西可以绝对匹配一个 URL?

或者确保从静态路由转到静态路由?

【问题讨论】:

  • 你能通过链接重定向分享文件夹结构和代码吗?
  • @FiodorovAndrei 添加了文件夹结构并更新了描述
  • 您是说如果您尝试在浏览器中访问localhost:3000/cz/cz 应用程序会呈现pages/[country]/[language]/index.js 中的内容吗?
  • @juliomalves 从浏览器访问它很好,但考虑链接组件,呈现pages/[country]/[language]/index.js 内容,实际上应该只是重新加载带有localhost:3000/cz/cz 内容的页面
  • 能否在您使用Link 组件的地方添加代码?

标签: javascript reactjs routes next.js


【解决方案1】:

按照 next.js documentation 预定义路由优先于动态路由,动态路由优先于捕获所有路由。 请看以下示例:

  • pages/post/create.js - 将匹配 /post/create
  • pages/post/[pid].js - 将匹配 /post/1、/post/abc 等,但不匹配 /post/create
  • pages/post/[...slug].js - 将匹配 /post/1/2、/post/a/b/c 等。但不匹配 /post/create、/post/abc

在您的情况下,您已经定义了预定义路由 cz/cz/index.js 并且该路由具有优先级

【讨论】:

  • 这就是问题所在,因为我的预定义路由cz/cz/index.js没有优先,动态路由会覆盖它,反之亦然
  • 您可以提供一个带有您项目结构的代码框示例吗?因为很难理解为什么动态路由会覆盖您的预定义路由。
  • 无法在codesandbox上重现问题,但在描述中提供了更多代码信息,也许有帮助
猜你喜欢
  • 1970-01-01
  • 2022-11-12
  • 2021-12-17
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 2021-11-18
相关资源
最近更新 更多