我正在尝试这个。但是使用String!
会收到错误,Errors:
Variable "$slug" of required type "String!" was not provided.
甚至可以查询(以下内容在localhost:8000 / ___ graphql上运行良好)。然后,我尝试了不带字符串的String
。然后错误消失了,但是我总是得到与markdown信息相同的内容。
有人有解决此问题的想法吗?
我的仓库:https://github.com/koji/portfolio
先谢谢您
错误
import { useStaticQuery, graphql } from "gatsby";
export const getPostData = () => {
const data = useStaticQuery(
graphql`
query getPostData($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
frontmatter {
title
date
}
html
}
}
`);
return data.markdownRemark;
};
返回相同的内容
import { useStaticQuery, graphql } from "gatsby";
export const getPostData = () => {
const data = useStaticQuery(
graphql`
query getPostData($slug: String) {
markdownRemark(fields: { slug: { eq: $slug } }) {
frontmatter {
title
date
}
html
}
}
`);
return data.markdownRemark;
};
试图获取降价文件的标题
import * as React from "react";
import Layout from "../components/layout";
import { getPostData } from "../components/hooks/getPost";
const Blog = () => {
const data = getPostData();
console.log(data);
return (
<Layout>
<h1>{data.frontmatter.title}</h1>
<p>{data.frontmatter.date}</p>
{data.html}
</Layout>
);
};
export default Blog;
gatsby-node.js
const path = require("path");
// onCreateNode API
module.exports.onCreateNode = ({node, actions}) => {
const { createNodeField } = actions;
// console.log(node);
if(node.internal.type === 'MarkdownRemark') {
const slug = path.basename(node.fileAbsolutePath, '.md');
createNodeField({
node,
name: 'slug',
value: slug
});
}
}
module.exports.createPages = async({ graphql, actions}) => {
const { createPage } = actions;
const blogTemplate = path.resolve('./src/templates/blog.tsx');
const res = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`);
res.data.allMarkdownRemark.edges.forEach(({node}) => {
createPage({
component: blogTemplate,
path: `/blog/${node.fields.slug}`,
context: {
slug: node.fields.slug,
}
});
})
}
答案 0 :(得分:1)
您必须在帖子模板中使用常规页面查询,即export const query = graphql...
原因是useStaticQuery
和<StaticQuery>
不会收到您传递给context
的{{1}}。