【问题标题】:Best practices for where to record data when using Gatsby, and how to import that data into gatsby.config.js or graphql使用 Gatsby 时在何处记录数据以及如何将数据导入 gatsby.config.js 或 graphql 的最佳实践
【发布时间】:2020-08-04 18:53:37
【问题描述】:

我跟着Gatsby Docs about data in 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
      }
    }
  }
`

我希望将我的网络应用程序中的所有数据与其余代码分开,并且全部包含在一个地方,例如,我可能有一个看起来像这样的文件

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 可能不是最好的方法,但也许我错了?

【问题讨论】:

    标签: javascript reactjs graphql gatsby


    【解决方案1】:

    您可以将数据移动到单个 JSON 文件中,然后使用 gatsby-transformer-json 将其放入 graphql。这样,您就可以使用 graphql 查询访问您的数据。

    PS。您也可以使用useStaticQuery 挂钩。

    在此处了解更多信息:https://www.gatsbyjs.org/packages/gatsby-transformer-json/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-24
      • 2016-08-21
      • 2016-07-03
      • 2011-11-30
      • 2010-10-08
      • 2010-10-11
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多