问题描述
我正在尝试使Gatsby的Ghost博客入门者适应我的需求。 当我试图格式化日期,以便在每个帖子页面中帖子下方显示日期时,例如MM-DD-YYYY。我使用了formatString。我使用graphiql UI界面创建了一个查询。但是我不知道如何在gatsby中使用它,尤其是在posts.js文件中。我遇到冲突,说我在同一文件中不能有2个查询,也没有变量定义问题。只是没有用。这是我的posts.js文件的代码:
import React from 'react'
import PropTypes from 'prop-types'
import { StaticQuery,graphql } from "gatsby"
import { Helmet } from 'react-helmet'
import postStyle from "./post.module.scss"
import Layout from '../components/layout'
import { MetaData } from '../components/common/Meta'
/**
* Single post view (/:slug)
*
* This file renders a single post and loads all the content.
*
*/
const Post = ({ data,location }) => {
const post = data.ghostPost
return (
<>
<MetaData
data={data}
location={location}
type="article"
/>
<Helmet>
<style type="text/css">{`${post.codeinjection_styles}`}</style>
</Helmet>
<Layout>
<div className={postStyle.postContainer}>
<article className="content">
{ post.feature_image ?
<figure className="post-feature-image">
<img className={postStyle.featureImageItself} src={ post.feature_image } alt={ post.title } />
</figure> : null }
<div className={postStyle.titleArea} styles={{ backgroundImage:`url($post.feature_image)` }}>
<h1 className={postStyle.postTitle}>{post.title}</h1>
<p>Published: {post.PostPublishedDate1}</p>
</div>
<section className={postStyle.postContent}>
{/* The main post content */ }
<section
className={postStyle.contentBody}
dangerouslySetInnerHTML={{ __html: post.html }}
/>
</section>
<div>
{post.tags_name}
</div>
</article>
</div>
</Layout>
</>
)
}
Post.propTypes = {
data: PropTypes.shape({
ghostPost: PropTypes.shape({
codeinjection_styles: PropTypes.object,title: PropTypes.string.isrequired,html: PropTypes.string.isrequired,feature_image: PropTypes.string,tags_name: PropTypes.string,}).isrequired,allGhostPost: PropTypes.shape({
published_at: PropTypes.string,location: PropTypes.object.isrequired,}
const PostPublishedDate1 = () => (
<StaticQuery
query={graphql`
query($slug: String!)
{
ghostPost(slug: { eq: $slug }) {
...GhostPostFields
}
allGhostPost(filter: {id: {},slug: { eq: $slug }}) {
edges {
next {
id
}
node {
id
published_at(formatString: "MM/DD/YYYY")
}
}
}
}
`}
render={data => <pre>{JSON.stringify(data,null,4)}</pre>}
></StaticQuery>
)
export default Post
这是我收到的错误消息的示例: gatsby error
解决方法
You can't use variables in Static Queries。而是导出页面查询以获取必要的信息,然后根据需要将其传递给子级。
也就是说,不要执行PostPublishedDate1
所需要的工作,只需执行以下操作:
export const query = graphql`
query PostQuery($slug: String!) {
ghostPost(slug: { eq: $slug }) {
...GhostPostFields
}
allGhostPost(filter: {id: {},slug: { eq: $slug }}) {
edges {
next {
id
}
node {
id
published_at(formatString: "MM/DD/YYYY")
}
}
}
}
`