我跟着一起 关于Gatsby中数据的Gatsby文档 他们向我展示了如何在siteMetadata块中创建一个graphql变量。
gatsby.config.js
module.exports = {
siteMetadata: {
title: `Title from siteMetadata`,
},
plugins: [
`gatsby-plugin-emotion`,
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography`,
},
},
],
}
然后可以使用graphql查询访问它。
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
export default ({ data }) => (
<Layout>
<h1>About {data.site.siteMetadata.title}</h1>
<p>
We're the only site running on your computer dedicated to showing the best
photos and videos of pandas eating lots of food.
</p>
</Layout>
)
export const query = graphql`
query {
site {
siteMetadata {
title
}
}
}
`
我希望将我的web应用中的所有数据与代码的其他部分分开,并且所有数据都包含在一个地方,例如,我可能有一个看起来像这样的文件
navLinks = ["Home", "About", "Contact"]
homePageIntro = "Hello! Thank you for visiting my website"
logo = 'https://aws.amazon.com/mys3.logo'
contactPhoto = 'https://aws.amazon.com/mys3.logo'
aboutPageFirstPar = 'This is the first paragraph on the about page'
aboutPageSecondPar = 'This is the Second paragraph on the about page'
或者把我的文本和链接分开到不同的文件中可能是更好的做法?
我只是有这样的感觉,把所有的数据变量插入到siteMetadata中可能不是最好的方法,但也许我错了?
你可以在一个JSON文件中移动你的数据,然后使用 gatsby-transformer-json
来放到graphql中。这样,你就可以使用graphql查询来访问你的数据了。
PS. 你也可以使用 useStaticQuery
钩。
在这里阅读更多关于它的信息。https:/www.gatsbyjs.orgpackagesgatsby-transformer-json