我正在使用查询变量slug为gatsby中的特定页面进行路由。因此,我使用项目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
它显示数据。
因此,如果我在不使用garapql查询变量或不从garapql获取数据的情况下运行模板,比如在模板中只打印这一行
<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 }
})
})
}
和markdownfiledojo 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
更新
我在我的模板中收到警告项目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
我想不出这里有什么错误。有人能帮忙吗?
从"graphql"->从"导入{graphql};盖茨比";
你还需要项目细节做下一步:
之前:
导出默认值((=>
之后:
函数ProjectDetails=((=>
导出默认ProjectDetails;