我使用gatsby-source-filesystem创建了多个数据源的配置,以便从文件系统中的不同位置获取不同的节点
// gatsby-config.js
module.exports = {
plugins: [
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'pages',
path: `${__dirname}/src/pages`
}
},
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'json',
path: `${__dirname}/src/data/json/`
}
}
]
}
在页面组件的上下文中,我创建了这些查询
export const query = graphql`
query {
allFile(filter: { sourceInstanceName: { eq: "json" } }) {
edges {
node {
name
}
}
}
}
`
export const pagesQuery = graphql`
query {
allFile(filter: { sourceInstanceName: { eq: "pages" } }) {
edges {
node {
name
}
}
}
}
`
在此组件页面中,我想显示每个查询的结果,但是我不清楚在组件中获取单个结果的过程
export default ({ data }) => {
console.log(data)
return (
<Layout>
<h1>About</h1>
<p>Lorem ipsum dolor sit amet</p>
{/*<Hobby hobbies={data.allFile.edges} />*/}
{/*<Hobby pages={data.allFile.edges} />*/}
</Layout>
)
}
这是页面组件/pages/about.js中的完整代码...
// src/pages/about.js
import React from "react"
import Layout from "../components/layout"
import { graphql } from "gatsby"
export default ({ data }) => {
console.log(data)
return (
<Layout>
<h1>About me</h1>
<p>Lorem ipsum dolor sit amet</p>
{/*<Hobby hobbies={data.allFile.edges} />*/}
{/*<Page pages={data.allFile.edges} />*/}
</Layout>
)
}
const Hobby = props => {
const hobbies = props.hobbies
return (
<div>
<h3>My hobbies</h3>
<ul>
{hobbies.map(hobby => (
<li>{hobby.node.name}</li>
))}
</ul>
</div>
)
}
const Page = props => {
const pages = props.pages
return (
<div>
<h3>Site pages</h3>
<ul>
{pages.map(hobby => (
<li>{hobby.node.name}</li>
))}
</ul>
</div>
)
}
export const query = graphql`
query {
allFile(filter: { sourceInstanceName: { eq: "json" } }) {
edges {
node {
name
}
}
}
}
`
export const pagesQuery = graphql`
query {
allFile(filter: { sourceInstanceName: { eq: "pages" } }) {
edges {
node {
name
}
}
}
}
`
记录数据值时,我得到执行的第一个查询的结果
答案 0 :(得分:1)
我相当确定Gatsby每个文件只使用1个graphql查询。您必须合并您的查询(您可以一次查询多个数据),使用不同的名称为它们加上别名,如下所示:
export const query = graphql`
query {
// alias
// vvvv
jsonData: allFile(filter: { sourceInstanceName: { eq: "json" } }) {
edges {
node {
name
}
}
}
pageData: allFile(filter: { sourceInstanceName: { eq: "pages" } }) {
edges {
node {
name
}
}
}
}
`
然后在组件中可以像这样使用它们:
export default ({ data }) => {
const { jsonData, pageData } = data
return (
...
)
}