![](/img/trans.png)
[英]Next.js dynamic link with catch-all (ie. [[...slug]]) does not work when using the "as" prop in Link component
[英]Next.js catch-all dynamic routing not working
我正在努力為我的 static 文檔頁面實現 nextjs 動態路由。
我目前的項目結構是這樣的。
.
├── pages
├── docs
├── [...slug].tsx <- want to route here other than `/docs`
├── index.tsx <- want to route here only `/docs`
│ ├── _app.tsx
│ └── index.tsx
└── next.config.js
例如,到達https//:example.com/docs
的用戶將被路由到docs/index.tsx
頁面,到達https//:example.com/docs/something
的用戶將被路由到docs/[...slug].tsx
頁面。
我使用 [...slug].tsx 因為我想用相同的邏輯處理/docs/
下的所有路由。 因此, /docs/ABCD
和/docs/ABCD/1234/
將由 [...slug].tsx 處理。
假設我在 index.tsx 中有Link
組件,如下所示。
// `doc.slug` can be "ABCD" or "ABCD/1234"
const Docs = (props) => {
const { docs } = props
return (
<div>
{docs.map((doc, i) => {
return (
<div key={i}>
<Link href={'/docs/' + doc.slug}>
<h1>GO</h1>
</Link>
</div>
)
})}
</div>
)
然后在我的[...slug].tsx
中。
export const getStaticPaths = async () => {
// Our Markdown files are stored in the docs/ directory
const DOCS_DIR = path.join(`${process.cwd() + '/src'}`, 'docs')
// Find all Markdown files in the posts/ directory
const docPaths = await glob(path.join(DOCS_DIR, '**/*.md'))
// For each filename, the slug is the filename without the .md extension
// and we split path which we use for our slug
const paths = docPaths.map((docPath) => {
const slug = docPath.split('docs/')[1].replace('.md', '')
// We should have "ABCD" and "ABCD/1234" for our staticPath
return { params: { slug: [slug] } } <- I think I do some wrong thing here?
})
// Return the possible paths
return { paths, fallback: false }
}
當前代碼適用於單個docs/ABCD
路由,但在docs/EFGH/1234
路由(嵌套路由)中返回 404 錯誤。
所以我嘗試添加一些新的路由來處理嵌套路由,如下所示,它確實有效。
.
├── pages
├── docs
├── [EFGH]
├── 1234.tsx <- It works!
├── [...slug].tsx <- want to route here other than `/docs`
├── index.tsx <- want to route here only `/docs`
│ ├── _app.tsx
│ └── index.tsx
└── next.config.js
這意味着當前的動態路由無法正常工作——我做錯了什么?
你是對的,陣列上有問題。 它應該像這樣返回。
return { params: { slug: ['ABCD','1234'] } }
參考: https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#paths
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.