问题描述
这似乎是一个相对普遍的问题。我正在尝试生成博客文章页面,但是遇到此错误,并且页面在加载时显示404。这意味着它们没有被生成。
exports.createPages = async ({ graphql,useStaticQuery,actions: { createPage } }) => {
const postQuery = graphql(`
{
gcms {
posts(where: { stage: PUBLISHED }) {
id
slug
}
}
}
`);
const {
gcms: { posts },} = useStaticQuery(postQuery);
posts.forEach(({ id,slug }) =>
createPage({
path: `/blog/${slug}`,component: require.resolve(`./src/templates/PostPage.js`),context: {
id: id,slug: slug,},})
);
};
/* eslint-disable react/prop-types */
import React from 'react';
import { graphql } from 'gatsby';
import Layout from "../components/layout";
//import galaxy from "../images/galaxy.jpg";
import SEO from "../components/SEO";
export const postPageQuery = graphql`
query PostPageQuery($id: ID!) {
gcms {
post(where: { id: $id }) {
title
slug
excerpt
postContentMarkdown
tags
author {
name
biography
}
SEO {
title
description
keywords
}
}
}
}
`;
const PostPage = ({data: {post}}) => {
return (
<Layout>
<SEO
keywords={[
`ui`,`ux`,]}
title="Blog" />
{post.slug}
</Layout>
);
};
export default PostPage;
解决方法
有些事情引起了我的注意,可能会解决您的问题。
-
gatsby-node.js
中useStaticQuery
的用法。您无需通过静态查询挂钩获取postQuery
数据,因为您在组件外部使用了挂钩。 -
where
过滤器的用法。根据{{3}},过滤数据的方法是使用filter
过滤器。另外,在过滤时,过滤的条件是字符串,因此必须用引号引起来。 -
当您通过上下文API将字段传递给
PostPage
时,应避免对所有gcms
进行过滤,因为您的模板具有该帖子的信息,因此无需重做再次使用相同的先前查询(与gatsby-node.js
相同),则不是最佳选择。因为我不知道您的数据结构如何,但应该对其进行重构,所以我会在那儿放。
将其应用于代码应如下所示。
gatsby-node.js:
exports.createPages = async ({ graphql,useStaticQuery,actions: { createPage } }) => {
const postQuery = graphql(`
{
gcms {
posts(filter: { stage: "PUBLISHED" }) {
id
slug
}
}
}
`);
let {posts}= postQuery.gcms;
posts.forEach(({ id,slug }) =>
createPage({
path: `/blog/${slug}`,component: require.resolve(`./src/templates/PostPage.js`),context: {
id: id,slug: slug,},})
);
};
PostPage.js:
/* eslint-disable react/prop-types */
import React from 'react';
import { graphql } from 'gatsby';
import Layout from "../components/layout";
//import galaxy from "../images/galaxy.jpg";
import SEO from "../components/seo";
export const postPageQuery = graphql`
query PostPageQuery($id: ID!) {
gcms {
post(filter: { id: $id }) {
title
slug
excerpt
postContentMarkdown
tags
author {
name
biography
}
seo {
title
description
keywords
}
}
}
}
`;
const PostPage = ({data: {post}}) => {
return (
<Layout>
<SEO
keywords={[
`ui`,`ux`,]}
title="Blog" />
{post.slug}
</Layout>
);
};
export default PostPage;
,
最后,我通过对项目进行完整的重组来解决此问题,并更新了最新版本的Gatsby,其中包括一个由gatsby入门,一个接一个的插件。最终成为插件冲突问题。我不确定确切是哪个插件,但很可能是其中之一:
gatsby-plugin-eslint
,gatsby-plugin-offline
,gatsby-plugin-root-import
或prop-types
NPM软件包。