组件本身不应进行任何查询。您应该将该部分抽象为模板。
首先,使用gatsby-node.js 中的createPages API 生成带有模板的博客文章,类似于:
...
createPage({
path: `${entity.entityTranslation.entityUrl.path}`,
component: path.resolve(`./src/templates/article.js`),
context: {
id: entity.entityTranslation.entityId,
languageId: lang.toUpperCase(),
},
})
...
您可以看到,在我的例子中,我将 ID 和语言 ID 传递给 article.js 中的模板查询:
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout/layout"
import ArticleFull from "../components/node/article-full";
export default ({ data }) => {
return (
<Layout>
<ArticleFull entity={data.drupal.nodeById.entityTranslation} />
</Layout>
)
}
export const query = graphql`
query($id: String!, $languageId: Drupal_LanguageId!) {
drupal {
nodeById(id: $id) {
... on Drupal_NodeArticle {
entityTranslation(language: $languageId) {
...ArticleFull
}
}
}
}
}
`;
查询检索每篇文章的数据。在我的例子中,源是 Drupal,所以这个查询对于 Drupal 来说是非常具体的,但是你应该能够根据你的 graphql 数据来定制它。请注意我在这里如何使用片段 (ArticleFull)。
我的实际组件是ArticleFull,看起来像这样:
import React from "react";
import "./article-full.scss"
const ArticleFull = (props) => {
return (
<div className="article-full">
<h1>{props.entity.entityLabel}</h1>
<div className="article-body" dangerouslySetInnerHTML={{ __html: props.entity.body.processed }}></div>
</div>
)
};
export default ArticleFull;