如何通过 getStaticPaths 使用多个嵌套动态路由?

Yas*_*idi 9 reactjs next.js

这是我的页面树

\n\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 _app.tsx\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 _document.tsx\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 index.tsx\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [type]\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [slug].tsx\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是 [slug] 页面的 getStaticPaths:

\n\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 _app.tsx\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 _document.tsx\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 index.tsx\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [type]\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [slug].tsx\n
Run Code Online (Sandbox Code Playgroud)\n\n

例如,页面看起来像这样\nhttp://localhost:3000/programming/some-slug

\n\n

当我转到某个帖子时,我收到此错误:

\n\n
\n

未在 getStaticPaths 中为 /[type]/[slug] 提供所需参数(类型)作为字符串

\n
\n\n

我只是不知道如何type向路由器提供参数。

\n

Sam*_*l G 8

上面的示例代码似乎是正确的,所以我会尝试两件事:

await1)我在呼叫时没有看到前缀getAllPosts(["slug"])- 这意味着您在获得数据之前就返回了。

除非这是设计,否则更改为:

const posts = await getAllPosts(["slug"]);
Run Code Online (Sandbox Code Playgroud)

2) 可能存在数据问题,并且您缺少预期的属性。我建议你getStaticPaths用一个简单的数组替换来检查:

const Test = (props) => {
    return (
       <>
           {props.slug}
       </>
    );
};

export async function getStaticProps({params}) {
    return {
        props: params
    }
}

export async function getStaticPaths() {
    const posts = [
        {
            mainTag: 'programming',
            slug: 'hello-world'
        },
        {
            mainTag: 'programming',
            slug: 'nextjs-101'
        },
    ];

    return {
        paths: posts.map((posts) => {
            return {
                params: {
                    type: posts.mainTag,
                    slug: posts.slug,
                },
            };
        }),
        fallback: false,
    };
}

export default Test;
Run Code Online (Sandbox Code Playgroud)