内容丰富和 gatsby js 获取

contenful and gatsby js fetching

我正在尝试通过在 gatsby 应用程序中使用 graphql 从 contentful 获取数据, 我就是这样做的:

type AllContentfulBlogs = { 
    allContentfulBlogs: {
            nodes: Array<{
            title?: string | null | undefined,
            tag?: string | null | undefined,
            read?: string | null | undefined,
            date?: string | null | undefined,
            picture?: Array<{
            gatsbyImageData: any } | null | undefined> | null | undefined,
            }> 
        };
}
interface BlogProps {
    data: AllContentfulBlogs;
  }

function BlogsIndex({data: {
    allContentfulBlogs:{nodes}
},}:BlogProps) {
  return (
    <Layout>
        <div>
            {nodes}
        </div>
        <Blogs  />
    </Layout>
  )
export const query = graphql`
query BlogsQuery {
allContentfulBlogs {
    nodes {
      title
      tag
      picture {
        gatsbyImageData
      }
      read
      date
    }
  }
}
`

所以当我尝试实施 nodes.title 时,我得到一个错误:

Property 'title' does not exist on type '{ title?: string | null | undefined; tag?: string | null | undefined; read?: string | null | undefined; date?: string | null | undefined; picture?: ({ gatsbyImageData: any; } | null | undefined)[] | null | undefined; }[]'

请问我该如何解决这个问题??

问题出在你的解构上。 BlogProps 适用于 data 而你得到 nodes,这是一个数组。

这种方法简单得多,但应该可行:

type AllContentfulBlogs = {
  allContentfulBlogs: {
    nodes: Array<{
      title?: string | null | undefined,
      tag?: string | null | undefined,
      read?: string | null | undefined,
      date?: string | null | undefined,
      picture?: Array<{
        gatsbyImageData: any } | null | undefined> | null | undefined,
    }>
  };
}

interface BlogProps {
  data: AllContentfulBlogs;
}

function BlogsIndex({data}:BlogProps) {
  return (
    <Layout>
      <div>
        {data.allContentfulBlogs.nodes[0].title}
      </div>
      <Blogs  />
    </Layout>
  )
  export const query = graphql`
    query BlogsQuery {
      allContentfulBlogs {
        nodes {
          title
          tag
          picture {
            gatsbyImageData
          }
          read
          date
        }
      }
    }
  `