简体   繁体   English

如何在 Next.js 的语言环境中获取 getStaticPaths 中的路径?

[英]How to get paths in getStaticPaths with locales in Next.js?

I'm using Strapi as a CMS, where I query for slugs, and I would like to have statically generated pages using getStaticPaths and getStaticProps in Next.js.我将 Strapi 用作 CMS,在其中查询 slug,并且我希望在 Next.js 中使用 getStaticPaths 和 getStaticProps 静态生成页面。

As I need to work with multiple locales, I have to map through the locales and get paths for each "Announcements" I'm getting from my query.由于我需要使用多个区域设置,因此我必须通过区域设置 map 并获取我从查询中获得的每个“公告”的路径。

The error message I'm getting is:我收到的错误消息是:

Error: A required parameter (slug) was not provided as a string in getStaticPaths for /updates/announcements/[slug]

This is my getStaticPaths:这是我的 getStaticPaths:

export async function getStaticPaths({ locales }: any) {
  const paths = await (
    await Promise.all(
      locales.map(async (locale: any) => {
        const { data } = await client.query({
          query: gql`
            query Announcements {
              announcements(locale: "${locale}") {
                data {
                  attributes {
                    slug
                    locale
                  }
                }
              }
            }
          `,
        });
        return {
          announcements: data.announcements.data,
          locale,
        };
      })
    )
  ).reduce((acc, item) => {
    item.announcements.map((p: any) => {
      acc.push({
        params: {
          slug:
            p.attributes.slug === "/" ? false : p.attributes.slug.split("/"),
        },
        locale: p.attributes.locale,
      });
      return p;
    });
    return acc;
  }, []);

  return {
    paths,
    fallback: false,
  };
}

If I console.log(paths) I get the following in the terminal:如果我 console.log(paths) 我在终端中得到以下信息:

[
  { params: { slug: [Array] }, locale: 'en' },
  { params: { slug: [Array] }, locale: 'en' },
  { params: { slug: [Array] }, locale: 'en' },
  { params: { slug: [Array] }, locale: 'da' },
  { params: { slug: [Array] }, locale: 'sv' },
  { params: { slug: [Array] }, locale: 'nb' }
]

I might think that Next.js don't want the slug to be an array, but I'm not entirely sure.我可能认为 Next.js 不希望 slug 成为一个数组,但我不完全确定。 What am I doing wrong?我究竟做错了什么?

You page uses dynamic routes named ( /updates/announcements/[slug] ), therefore the param slug is required in paths .您的页面使用名为 ( /updates/announcements/[slug] ) 的动态路由,因此paths中需要参数slug

From the Next.js getStaticPaths documentation :来自Next.js getStaticPaths文档

The paths key determines which paths will be pre-rendered. paths键决定了哪些路径将被预渲染。 For example, suppose that you have a page that uses Dynamic Routes named pages/posts/[id].js .例如,假设您有一个使用名为pages/posts/[id].js的动态路由的页面。 If you export getStaticPaths from this page and return the following for paths :如果您从此页面导出getStaticPaths并为paths返回以下内容:

 return { paths: [ { params: { id: '1' }}, { params: { id: '2' }, // with i18n configured the locale for the path can be returned as well locale: "en", }, ], fallback: ... }

Then, Next.js will statically generate /posts/1 and /posts/2 during next build using the page component in pages/posts/[id].js .然后,Next.js 将next build期间使用pages/posts/[id].js中的页面组件静态生成/posts/1/posts/2

The slug param can only be a string since it's used to generate routes. slug参数只能是一个string ,因为它用于生成路由。 As you found when logging paths , you were trying to pass slug: [Array] .正如您在记录paths时发现的那样,您试图传递slug: [Array]

The problem in the question's code snippet is this expression to assign a slug :问题代码片段中的问题是这个表达式分配一个slug

// ...
params: {
  slug: p.attributes.slug === "/" ? false : p.attributes.slug.split("/"), // 👈
},
// ...

This expression will either assign false (boolean) or an array of substrings (see the docs for String.prototype.split() ).此表达式将分配false (布尔值)或子字符串数组(请参阅String.prototype.split()的文档)。

In this case, as confirmed in a comment above, simply passing the slug as a string solves the issue.在这种情况下,正如上面的评论所证实的那样,只需将 slug 作为字符串传递即可解决问题。

The confusion likely came from following a tutorial that uses an optional catch-all route ( pages/[[...slug]] ) instead of regular dynamic routes ( pages/[slug] ) ( ref ).混淆可能来自于使用可选的包罗万象的路由( pages/[[...slug]] ) 而不是常规动态路由 ( pages/[slug] ) ( ref ) 的教程。

From the Next.js getStaticPaths documentation again:再次来自Next.js getStaticPaths文档

  • If the page name is pages/posts/[postId]/[commentId] , then params should contain postId and commentId .如果页面名称是pages/posts/[postId]/[commentId] ,那么 params 应该包含postIdcommentId
  • If the page name uses catch-all routes like pages/[...slug] , then params should contain slug (which is an array).如果页面名称使用像pages/[...slug]这样的包罗万象的路由,那么 params 应该包含slug (它是一个数组)。 If this array is ['hello', 'world'] , then Next.js will statically generate the page at /hello/world .如果这个数组是['hello', 'world'] ,那么 Next.js 将在/hello/world静态生成页面。
  • If the page uses an optional catch-all route, use null , [] , undefined or false to render the root-most route.如果页面使用可选的包罗万象的路由,请使用null[]undefinedfalse来呈现最根路由。 For example, if you supply slug: false for pages/[[...slug]] , Next.js will statically generate the page / .例如,如果您为pages/[[...slug]]提供slug: false ,则 Next.js 将静态生成页面/

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

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