Javascript 如何将页面模板拆分为单独的组件,每个组件都查询数据?
我在盖茨比创建了一个博客帖子模板。现在,我想将页面分成多个功能组件,每个功能组件都通过Javascript 如何将页面模板拆分为单独的组件,每个组件都查询数据?,javascript,reactjs,graphql,gatsby,Javascript,Reactjs,Graphql,Gatsby,我在盖茨比创建了一个博客帖子模板。现在,我想将页面分成多个功能组件,每个功能组件都通过useStaticQuery拉入数据 据我所知,Graphql变量仅适用于页面查询,模板文本也不例外: const Slideshow=props=>{ const data=useStaticQuery( 图形ql` 质疑{ contentfulPost(slug:{eq:${props.slug}}}){ 图像{ 标题 描述 尺寸 } } } ` ... } 如何让组件知道要查询哪些数据?组件本身不应该进
useStaticQuery
拉入数据
据我所知,Graphql变量仅适用于页面查询,模板文本也不例外:
const Slideshow=props=>{
const data=useStaticQuery(
图形ql`
质疑{
contentfulPost(slug:{eq:${props.slug}}}){
图像{
标题
描述
尺寸
}
}
}
`
...
}
如何让组件知道要查询哪些数据?组件本身不应该进行任何查询。您应该将该部分抽象为模板 首先,使用
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
}
}
}
}
}
`;
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;