简体   繁体   English

Next.js 来自“pages/[...slug].js”的路由不起作用

[英]Next.js routing from "pages/[...slug].js" not working

This is how my pages folder looks like:这是我的页面文件夹的样子:

pages
   index.js  
   [...slug].js

I know that the problem lies for sure in the fact that I am using catch all routes directly in the pages folder, because I tried with a "pages/page/[...slug].js structure and everything works fine.我知道问题肯定在于我直接在pages文件夹中使用 catch all routes,因为我尝试使用“pages/page/[...slug].js 结构并且一切正常。

When navigating using the Link component from the index.js page to a [...slug].js page (eg /careers or /blog), everything works fine .当使用 Link 组件从 index.js 页面导航到 [...slug].js 页面(例如 /careers 或 /blog)时,一切正常

BUT when navigating from a [...slug].js page (eg /contact) to another similar page (eg /blog) only the URL changes correctly, but the content of the page stays the same , so there is no rerendering.但是当从 [...slug].js 页面(例如 /contact)导航到另一个类似页面(例如 /blog)时,只有 URL 正确更改,但页面内容保持不变,因此没有重新呈现。

Note: Navigating from a [...slug].js page back to the root file (href="/") works.注意:从 [...slug].js 页面导航回根文件 (href="/") 有效。

TLDR: TLDR:
When returning the set of props from your getStaticProps or getServerSideProps function, return a "key" prop and assign it a unique value, so that react is able to differentiate between the two pages that are served from the same dynamic path.当从 getStaticProps 或 getServerSideProps function 返回一组道具时,返回一个“关键”道具并为其分配一个唯一值,以便 React 能够区分从同一动态路径提供的两个页面。

I found the solution to the "problem" in github issue from last year: https://github.com/vercel/next.js/issues/9992我在去年的 github 问题中找到了“问题”的解决方案: https://github.com/vercel/next.js/issues/9992

You can find a clear solution reading through the issue I linked.您可以通过阅读我链接的问题找到一个明确的解决方案。

Make each page its own file within your pages folder.在您的页面文件夹中使每个页面成为自己的文件。 For example, you could have:例如,您可以:

pages/
  index.js
  contact.js
  careers.js
  blog.js

Each file should export a default function that returns JSX.每个文件都应导出返回 JSX 的默认 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM