簡體   English   中英

Gatsby“以編程方式從數據創建頁面”無效

[英]Gatsby “Creating Pages from Data Programatically” Doesn't Work

我正在嘗試這個。 但是用String! 收到錯誤, Errors: Variable "$slug" of required type "String!" was not provided. 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,
       }
     });
   })
}

您必須在帖子模板中使用常規頁面查詢,即export const query = graphql...

原因是useStaticQuery<StaticQuery>不會收到您傳遞給createPagecontext

官方文檔:靜態查詢與頁面查詢的區別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM