javascript - 您如何将页面模板拆分为单独的组件,每个组件都查询数据?
问题描述
我在 Gatsby 中创建了一个博客文章模板。现在我想将页面分解为功能组件,每个组件都通过useStaticQuery
.
据我所知,Graphql 变量仅适用于页面查询,模板文字也不例外:
const Slideshow = props => {
const data = useStaticQuery(
graphql`
query {
contentfulPost(slug: { eq: "${ props.slug }" }) {
images {
title
description
sizes
}
}
}
`
...
}
如何让组件知道要查询哪些数据?
解决方案
组件本身不应进行任何查询。您应该将该部分抽象为模板。
首先,使用createPages
APIgatsby-node.js
生成带有模板的博客文章,例如:
...
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;
推荐阅读
- c - i2c 传输,stm32f103 作为 Master,STOP 条件生成问题
- c# - 在 ASP.Net 中实现和生成多个动态 SiteMapNode
- json - 使用 `curl` 的 API 调用在 Swift 中不起作用
- jquery - 另一个表单的另一个 ajax 函数不起作用
- css - 如何显示行的交替红色和绿色?
- python - 如何获得方向
在tkinter? - c - 为什么 scanf_s 不能在 Visual Studio 以外的任何地方工作?
- c++ - r 值引用是如何在这里传递的?
- javascript - 为什么我的搜索查询结果不佳?
- c++ - 为什么 clang 不能将元组的构造限制为显式?