您只需遵循有关从 JSON 采购的文档 https://www.gatsbyjs.com/docs/how-to/sourcing-data/sourcing-from-json-or-yaml/.
也就是说,从 JSON 本地文件获取数据时不需要使用 GraphQL,只需导入对象即可,例如:
import React from "react"
import JSONData from "../../content/My-JSON-Content.json"
const SomePage = () => (
<div style={{ maxWidth: `960px`, margin: `1.45rem` }}>
<ul>
{JSONData.compdata.map((data, index) => {
return <li key={`content_item_${index}`}>{data.title}</li>
})}
</ul>
</div>
)
export default SomePage
在这种情况下,您可以将 JSON 数据导入为JSONData
并循环遍历数组compdata
.
但是,如果您仍然想使用 GraphQL,则需要使用gatsby-transformer-json https://www.gatsbyjs.com/plugins/gatsby-transformer-json/插件,它将从 JSON 源创建可查询的 GraphQL 节点:
通过以下方式安装:
npm install gatsby-transformer-json
并用它你的gatsby-config.js
:
module.exports = {
plugins: [
`gatsby-transformer-json`,
{
resolve: `gatsby-source-filesystem`,
options: {
path: `./src/your/json/folder`,
},
},
],
}
节点的别名将依赖于您的文件夹结构和命名(尚未提供),在文档示例中,给定letters.json
例如:
[{ "value": "a" }, { "value": "b" }, { "value": "c" }]
所以在你的 GraphiQL 游乐场中(localhost:8000/___graphql
)你将能够
查询allLettersJson
node:
{
allLettersJson {
edges {
node {
value
}
}
}
}
您可以添加一个typeName
修复命名的选项,例如:
{
resolve: `gatsby-transformer-json`,
options: {
typeName: `Json`,
},
},
在这种情况下,创建的节点将是allJson
.