如何在GatsbyJS的React组件中使用GraphQL中的数据



我试图查询一个特定的类别标题并在div内返回它。它给了我以下错误消息:

TypeError: can't access property "node", data.edges is undefined

我的文件:

import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import styled from "styled-components"
import { H3, BodyMain } from "../styles/TextStyles"
export default function CategorySection() {
const data = useStaticQuery(graphql`
query categoryQuery {
allGraphCmsCategory(filter: { title: { eq: "CSS" } }) {
edges {
node {
title
slug
description
}
}
}
}
`)
return (
<Wrapper>
<ContentWrapper>
<TextWrapper>
<Title>Browse by Categories</Title>
<Description>
Use the category tags to narrow down what you are looking for.
</Description>
</TextWrapper>
<CategoryWrapper>
<Categories>{data.edges.node.title}</Categories>
</CategoryWrapper>
</ContentWrapper>
</Wrapper>
)
}
const Wrapper = styled.div``
const ContentWrapper = styled.div``
const TextWrapper = styled.div``
const Title = styled(H3)``
const Description = styled(BodyMain)``
const CategoryWrapper = styled.div``
const Categories = styled.div``

我相信我的查询是正确的,因为我能够在http://localhost:8000/___graphql

上看到结果当我测试它并看到它工作时,我想映射所有类别并为每个类别创建单独的页面。

你能给我指路吗?

您的查询看起来不错,但是,您需要访问嵌套对象,如GraphQL所示,在您的情况下,这应该可以工作:

export default function CategorySection() {
const data = useStaticQuery(graphql`
query categoryQuery {
allGraphCmsCategory(filter: { title: { eq: "CSS" } }) {
edges {
node {
title
slug
description
}
}
}
}
`)
console.log("your data is", data.allGraphCmsCategory.edges) // use to access to the nested data data.allGraphCmsCategory.edges[0].node.title
return (
<Wrapper>
<ContentWrapper>
<TextWrapper>
<Title>Browse by Categories</Title>
<Description>
Use the category tags to narrow down what you are looking for.
</Description>
</TextWrapper>
<CategoryWrapper>
<Categories>{data.edges.node.title}</Categories>
</CategoryWrapper>
</ContentWrapper>
</Wrapper>
)
}

注意,在数据内部,您首先需要访问allGraphCmsCategory并继续跟踪对象树。我已经假设(因为all关键字在allGraphCmsCategory),结果将有多个边节点(数组),这就是为什么edges[0].

或者,您可以使用StaticVersion组件:

export default function CategorySection() {
return (
<StaticQuery
query={graphql`
query categoryQuery {
allGraphCmsCategory(filter: { title: { eq: "CSS" } }) {
edges {
node {
title
slug
description
}
}
}
}
`}
render={data => {
console.log(data);
return (
<Wrapper>
<ContentWrapper>
<TextWrapper>
<Title>Browse by Categories</Title>
<Description>
Use the category tags to narrow down what you are looking for.
</Description>
</TextWrapper>
<CategoryWrapper>
<Categories>{data.allGraphCmsCategory.edges[0].node.title}</Categories>
</CategoryWrapper>
</ContentWrapper>
</Wrapper>
)
}}
/>
)
}

设置为动态:

{data.allGraphCmsCategory.edges.map(item=>{
return <Categories>{item.title}</Categories>
})}

最新更新