简体   繁体   English

getStaticPaths - data.map 不是 function

[英]getStaticPaths - data.map is not a function

I am using Strapi with Next.js for my blog project我在我的博客项目中使用带有 Next.js 的 Strapi

I am trying to make dynamic pages by using [id].js inside pages/posts/[id].js我正在尝试通过在 pages/posts/[id].js 中使用 [id].js 来制作动态页面

But, the problem is when I try to map through the API of Strapi inside getStaticPaths() it gives me an error with data.map is not defined但是,问题是当我尝试通过 getStaticPaths() 中 Strapi 的 API 尝试 map 时,它给了我一个数据错误。map 未定义

Note:- I am using NextJS V12.0.8 with Strapi V4.0.4注意:- 我使用 NextJS V12.0.8 和 Strapi V4.0.4

Below is my code下面是我的代码

export async function getStaticPaths() {
  const postsRes = await axios.get("http://localhost:1337/api/posts?populate=image");
 
  const paths = postsRes.map((post) => {
    return { params: {id: post.id.toString()} }
  });

  // const paths = { params: {id: '1' } }
    
  return {
    paths,
    fallback: false
 
  }
 
}

Complete [id].js Page Code Link - https://pastebin.com/SnzLirys完成[id].js页面代码链接 - https://pastebin.com/SnzLirys

Error Screenshot - https://prnt.sc/26ha6z5错误截图 - https://prnt.sc/26ha6z5

Somehow axios is the problem.不知何故 axios 是问题所在。 For next generations - try get data with fetch instead of axios, in my case it works.对于下一代 - 尝试使用 fetch 而不是 axios 获取数据,在我的情况下它可以工作。

apparently you need to set up a context to use axios inside that function, or you can try to format the axios response to json.stringfy and then use json.parse in it. apparently you need to set up a context to use axios inside that function, or you can try to format the axios response to json.stringfy and then use json.parse in it. or just use fetch.或者只是使用获取。

in case you are using next api folder, don't call fetch or axios here, just make the query as if you were in node如果您使用的是下一个 api 文件夹,请不要在此处调用 fetch 或 axios,只需像在节点中一样进行查询

export async function getStaticPaths() {
      const get = await fetch("url")
      const data = await get.json()
      
      data.map(item => console.log(item))
     
      const paths = data.map((post) => {
        return { params: {id: post.id.toString()} }
      });
    
      // const paths = { params: {id: '1' } }
        
      return {
        paths,
        fallback: false
     
      }
     
    }

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

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