Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将页面模板拆分为单独的组件,每个组件都查询数据?_Javascript_Reactjs_Graphql_Gatsby - Fatal编程技术网

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;