如何解决使用查询变量时 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 = () => ;
导出默认项目详细信息;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。