【问题标题】:Filter get static paths Nextjs过滤获取静态路径 Nextjs
【发布时间】:2022-07-29 16:07:59
【问题描述】:

如何仅返回来自getStaticPaths 的过滤路径?

这会返回整个帖子

export async function getStaticPaths() {
  const { data } = await axios.get(`${url}/category`, config);

 const paths = data.map((post) => {
    
      return {
        params: { postId: post.id },
      };
    
  });


  return {
    paths,
    fallback: false
  }
}

这是我重试的

export async function getStaticPaths() {
  const { data } = await axios.get(`${url}/category`, config);

  const paths = data.filter((post) => {
     if (post.isActive) {
      return { params: { postId: post.id } }
     }
  })

  return {
    paths,
    fallback: false
  }
}

错误信息

> Build error occurred
Error: Additional keys were returned from `getStaticPaths` in page "/product/[packageAlias]". URL Parameters intended for this dynamic route must be nested under the `params` key,

【问题讨论】:

  • 您将过滤器与地图混淆了。 Filter 只是过滤掉项目,所以你的 return { params: { postId: post.id } }return true 相同

标签: javascript reactjs next.js getstaticprops


【解决方案1】:

filter方法会在过滤后返回相同的对象格式,所以你需要mapfilter之后,你可以使用flatMap方法同时做。

const paths = data.flatMap((post) => {
   return post.isActive ? [{ params: { postId: post.id } }] : [];
})

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2022-07-14
    • 1970-01-01
    • 2021-08-12
    • 2020-12-27
    • 2022-11-14
    • 2020-07-06
    • 2020-12-19
    相关资源
    最近更新 更多