Next.js-GetStaticPaths TypeError

时间:2020-09-08 20:35:38

标签: node.js next.js

我对Next.JS的getStaticPaths有以下问题:

TypeError:cias.map不是函数 https://i.stack.imgur.com/IVZDp.png

有人可以帮我吗?

代码:

import React from 'react'
import { Container } from '../../../styles/pages/container'
import { GetStaticProps, GetStaticPaths } from 'next'
import fetch from 'isomorphic-unfetch'

    export const getStaticPaths: GetStaticPaths = async () => {
      const res = await fetch('http://localhost:3000/api/infocadcias')
      const cias = await res.json()
    
      const paths = cias.map(cia => ({
        params: { id: cia.ID.toString() }
      }))
    
      return { paths, fallback: false }
    }
    
    export const getStaticProps: GetStaticProps = async ({ params }) => {
      const res = await fetch(`http://localhost:3000/infocadcias/${params.id}`)
      const cia = await res.json()
    
      return cia
    }
    
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    export default function InfoCia({ cia }) {
      return (
        <Container>
          <ul>
            {cia.map(p => (
              <li className="cia" key={p.ID}>
                <span>Name: {p.Name}</span>
              </li>
            ))}
          </ul>
        </Container>
      )
    }

1 个答案:

答案 0 :(得分:0)

编辑:我在下面回答了错误的问题,但是您仍然应该看一下。因为cias不是数组,所以您收到该错误。如果仍然没有解决方案,请尝试记录该变量并使用结果更新您的问题。可能类似于{cias: [...]},在这种情况下,您需要将映射更改为cias.cias.map(...)或在分配const { cias } = await res.json()时解构变量


getStaticProps函数中,您未以正确的格式返回。您需要使用props键返回一个对象,如下所示:

{
  props: {
    cia: cia
  }
}

您可以在以下位置参考有关getStaticProps的NextJS文档:https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

如果这不能解决问题,则应确保await res.json()返回一个数组。

带有更新的完整示例:

import React from 'react'
import { Container } from '../../../styles/pages/container'
import { GetStaticProps, GetStaticPaths } from 'next'
import fetch from 'isomorphic-unfetch'

    export const getStaticPaths: GetStaticPaths = async () => {
      const res = await fetch('http://localhost:3000/api/infocadcias')
      const { cias } = await res.json()
       
      const paths = cias.map(cia => ({
        params: { id: cia.ID.toString() }
      }))
    
      return { paths, fallback: false }
    }
    
    export const getStaticProps: GetStaticProps = async ({ params }) => {
      const res = await fetch(`http://localhost:3000/infocadcias/${params.id}`)
      const { cia } = await res.json()
    
      return {
        props: {
          cia: cia
        }
      }
    }
    
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    export default function InfoCia({ cia }) {
      return (
        <Container>
          <ul>
            {cia.map(p => (
              <li className="cia" key={p.ID}>
                <span>Name: {p.Name}</span>
              </li>
            ))}
          </ul>
        </Container>
      )
    }
    ```