我有以下文件夹结构:
在 docu-{mdx.frontmatter__key}-{mdx.frontmatter__slug}.js 中我有以下内容:
import * as React from 'react'
import Layout from '../../components/layout/layout'
import SingleDocuLayout from './components/single-docu-layout/single-docu-layout'
import Seo from '../../components/seo'
import { graphql } from 'gatsby'
import { GatsbyImage, getImage } from 'gatsby-plugin-image'
const SingleDocu = ({ data, children }) => {
const image = getImage(data.mdx.frontmatter.heroImage)
return (
<Layout pageTitle={data.mdx.frontmatter.title}>
<p>Posted: {data.mdx.frontmatter.date}</p>
<GatsbyImage
image={image}
alt={data.mdx.frontmatter.heroImageAlt}
/>
{children}
<SingleDocuLayout />
</Layout>
)
}
export const query = graphql`
query($id: String) {
mdx(id: {eq: $id}) {
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
heroImageAlt
heroImage {
childImageSharp {
gatsbyImageData
}
}
}
}
}
export const Head = ({ data }) => <Seo title={data.mdx.frontmatter.title} />
export default SingleDocu`
在这里我可以从文件中获取数据。
在overview.js中我有以下代码:
import * as React from 'react'
import { useStaticQuery,graphql } from 'gatsby'
import { GatsbyImage, getImage } from 'gatsby-plugin-image'
import {
Wrapper,
BackgroundAsset,
BackgroundImage,
} from "./style";
const Overview = ({ data, children }) => {
const query = useStaticQuery(graphql`
query {
mdx{
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
heroImageAlt
heroImage {
childImageSharp {
gatsbyImageData
}
}
}
}
}
`)
const image = getImage(data.mdx.frontmatter.heroImage)
return (
<>
"overview"
</>
/* <Wrapper data-testid="overview">
<BackgroundAsset>
<BackgroundImage>
<GatsbyImage
//image={image}
//alt={data.mdx.frontmatter.heroImageAlt}
/>
</BackgroundImage>
</BackgroundAsset>
</Wrapper> */
)
}
export default Overview
尝试使用或不使用 useStaticQuery 我收到以下错误: 无法读取未定义的属性(读取“mdx”) ./src/pages/archive/components/single-doc-sections/overview/overview.js:30
28 | } 29 | 29 `)
30 | const image = getImage(data.mdx.frontmatter.heroImage) | ^ 31 |返回 ( 32 | 32 <> 33 | 33 「概览」
有人可以帮我解决这个问题吗? 谢谢
我想知道如何才能成功获取数据。 我尝试使用 useStaticQuery 进行 graphql 查询,但没有得到相同的错误