我被困了几个小时,不知道出了什么问题。我是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
})
})
})
}
templates / 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
}
}
`
答案 0 :(得分:0)
我决定只列出项目,而不是链接到每个项目。这样,我只需要在文件中查询,而不是通过gatsby-node.js传递每个对象并在模板文件中获取正确的对象。
import React from "react"
// import { Link } from "gatsby"
import { graphql } from 'gatsby'
import Layout from "../components/layout"
import SEO from "../components/seo"
const Projects = ({data}) => (
<Layout>
<SEO title="Projects" />
<h1>Personal Projects</h1>
{data.allProjectsJson.edges.map((project, index) => {
console.log(project)
return (
<a
key={index}
style={projectContainerStyles}
href={project.node.url}
target="_blank"
rel="noopener noreferrer"
>
<h2>{project.node.name}</h2>
{project.node.description}
</a>
)
})}
<p>You can see my external portfolio
<a
href="https://anthonyzamarro.github.io/az_portfolio/"
target="_blank"
rel="noopener noreferrer">
here!
</a>
</p>
</Layout>
)
const projectContainerStyles = {
marginBottom: '2rem',
background: 'turquoise',
padding: '8px',
borderRadius: '5px',
boxShadow: '1px 3px 2px rgb(155,155,155)',
'display': 'block',
'color': '#000',
textDecoration: 'none'
}
export const projectQuery = graphql`
query projectQuery {
allProjectsJson {
edges {
node {
id
name
description
url
}
}
}
}`
export default Projects