使用查询变量时 Gatsby 运行时错误

问题描述

我正在使用查询变量 slug 来路由 gatsby 中的特定页面。所以我使用模板 project-datails.js 来创建页面

所以 project-datails.js 和 graphql 查询变量是这样的


import React from "react"
import Layout from "../components/Layout"
import { graphql } from "graphql"


import * as styles from "../styles/project-details.module.css"


export default function ProjectDetails({ data}) {
  console.log(data)

 
  const { title,stack } = data.markdownRemark.frontmatter
  return (
    <Layout>
      <div className={styles.details}>
        <h2>{title}</h2>
        <h3>{stack}</h3> 
        <h1>Hello</h1>
       </div>
    </Layout>
  )
}

export const query = graphql`
  query ProjectDetails($slug: String) {
    markdownRemark(frontmatter: { slug: { eq: $slug } }) {
      html
      frontmatter {
        stack
        title
        }
    }
  }
`

当我记录数据时,它显示未定义。当我在

上运行相同的查询
 http://localhost:8000/___graphql

显示数据。

因此,如果我在不使用garaphql 查询变量或不从garaphql 中获取数据的情况下运行模板,例如只在模板内打印这一行

<h1>Hello</h1>

它工作正常。

所以当我使用查询变量时,它显示运行时错误

这个查询变量 slug 我是从 gatsby-node.js 传过来的

const path = require(`path`)

exports.createPages = async ({ graphql,actions }) => {

  const { data } = await graphql(`
    query Articles {
      allMarkdownRemark {
        nodes {
          frontmatter {
            slug
          }
        }
      }
    }
  `)

  data.allMarkdownRemark.nodes.forEach(node => {
    actions.createPage({
      path: '/projects/'+ node.frontmatter.slug,component: path.resolve('./src/templates/Project-details.js'),context: {slug: node.frontmatter.slug }
    })
  })

}

和 markdownfile dojo-coffee-house.md 看起来像这样

---
title: The Dojo Coffee House
stack: HTML & CSS
slug: the-dojo-coffee-house
date: 2021-01-01T00:00:00+00:00
thumb: ../images/thumbs/coffee.png
featuredImg: ../images/featured/coffee-banner.png
---

Lorem ninja ipsum dolor sit amet,consectetuer adipiscing elit,sed diam nonummy nibh euismod tincidunt

更新

我在我的模板 project-datails.js 中收到警告

                                                 
 warning  In page templates only a default export of a valid React component and the named export of a page
query is allowed.
        All other named exports will cause Fast Refresh to not preserve local component state and do a full refresh.

        Please move your other named exports to another file. Also make sure that you only export page queries that
use the "graphql" tag from "gatsby".
  limited-exports-page-templates

我无法弄清楚这里的错误是什么。有人可以帮忙吗?

解决方法

import { graphql } from "graphql" -> import { graphql } from "gatsby"

您还需要为 ProjectDetails 做下一步:

之前:

导出默认值 () => ;

之后:

function ProjectDetails = () => ;

导出默认项目详细信息;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...