【问题标题】:Rendering JSON with GraphQL in GatsbyJS在 GatsbyJS 中使用 GraphQL 渲染 JSON
【发布时间】: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:.... })

标签: graphql gatsby


【解决方案1】:

我决定简单地列出项目,而不是链接到每个项目。这样,我只需在文件中进行查询,而不是通过 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


【讨论】:

    猜你喜欢
    • 2020-06-18
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2021-11-20
    • 2014-07-16
    • 2021-04-29
    • 2020-11-15
    相关资源
    最近更新 更多