繁体   English   中英

Next.js 包罗万象的动态路由不起作用

[英]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.

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