Gatsby“以编程方式从数据创建页面”无效

时间:2019-08-09 01:11:53

标签: javascript graphql gatsby

我正在尝试这个。但是使用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,
       }
     });
   })
}

1 个答案:

答案 0 :(得分:1)

您必须在帖子模板中使用常规页面查询,即export const query = graphql...

原因是useStaticQuery<StaticQuery>不会收到您传递给context的{​​{1}}。

Official docs: How Static Query Differ from Page Query