【发布时间】:2019-08-01 06:49:31
【问题描述】:
我被困了好几个小时,我不知道出了什么问题。我是 GraphQL 和 Gatsby 的新手。
我有一个我正在尝试渲染的 JSON 文件。每个对象都有自己的 url 路径。我可以使用 GraphQL 查询数据,在我的 gatsby-node.js 文件中设置 CreatePages,然后在我的模板文件中再次查询,但由于某种原因,我只能在模板文件中获得 null。
我很确定我也正确使用了 gatsby-plugin-transformer-json。我现在很茫然。非常感谢任何帮助。
gatsby-node.js
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
// You can delete this file if you're not using it
const path = require('path');
exports.createPages = ({actions, graphql}) => {
const { createPage } = actions;
const postTemplate = path.resolve(`src/templates/post.js`);
const projectTemplate = path.resolve(`src/templates/project.js`);
return graphql(`{
allProjectsJson {
edges {
node {
id
name
description
path
}
}
}
allMarkdownRemark {
edges {
node {
html
id
frontmatter {
path
title
date
}
}
}
}
}`)
.then(res => {
if(res.errors) {
return Promise.reject(res.errors);
}
// blogs
res.data.allMarkdownRemark.edges.forEach(({node}) => {
createPage({
path: node.frontmatter.path,
component: postTemplate
})
})
// projects
res.data.allProjectsJson.edges.forEach(({node}) => {
createPage({
path: node.path,
component: projectTemplate
})
})
})
}
模板/project.js
import React from 'react';
import { graphql } from 'gatsby'
import Layout from "../components/layout"
// import Helmet from 'react-helmet';
export default function Project({data}) {
const { projectsJson: project } = data;
// this results in null???
console.log(data)
return (
<Layout>
<div>
<h1>Projects!!!</h1>
<p>One single</p>
</div>
</Layout>
);
}
export const projectQuery = graphql`
query ProjectByPath($path: String!) {
projectsJson(path: { eq: $path }) {
name
path
description
}
}
`
【问题讨论】:
-
graphiql 中
allProjectsJson查询的输出是什么? -
@DerekNguyen 使用 Gatsby 的 Graphi 接口的输出是我指定的 JSON 数据。那工作得很好。由于某种原因,当我在我的模板文件中查询时,我收到了 null。
-
它是注销所有 json 节点的
null,还是只注销一个?在您的项目模板中,您是否尝试过注销props.pageContext以查看path是否正确? -
哦,等等,您似乎没有为您的 json 节点传递上下文 — 试试
createPage({ path: node.path, context: { path: node.path }, component:.... })