0

我正在使用查询变量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
        }
    }
  }
`

当我记录数据时,它显示undefined。当我运行相同的查询时

 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

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

4

1 回答 1

1

从“graphql”导入 { graphql } -> 从“gatsby”导入 { graphql }

你还需要 ProjectDetails 做下一步:

前:

导出默认 () => ;

后:

函数项目详细信息 = () => ;

导出默认 ProjectDetails ;

于 2021-04-05T08:51:00.330 回答