reactjs - 如何使用 gatsby 将值传递给 GraphQL 查询并使用react?

标签 reactjs graphql gatsby

我正在尝试通过项目 ID 使用 graphql 从我的数据库中获取某些内容,但我不确定如何将值传递给 graphql 以获取它。


import React from "react"
import { useStaticQuery, graphql } from "gatsby"

const MyCustomComponent = (props) => {
  // How do I pass this value
  let theValueIWantToPass = 5

  // into this query
  const data = useStaticQuery(graphql`
    query MyQuery {
      mongodbItems(id: {eq: "5"}){
        id
      }
    }
  `)


  return (
    <div>

    </div>
  )
}


export default MyCustomComponent

最佳答案

静态查询之所以称为“静态”,是因为它们具有在您运行 gatsby build 时计算的单个不变值。 .因此,就其本质而言,它们不能不接受变量。
根据您要实现的目标,您可能会使用 page query .它可以接受参数,但这些参数对于每个页面都是固定的(换句话说:当您运行 gatsby build 时,每个页面都会执行一个查询,因此您必须在构建时知道每个页面的变量)。
在构建步骤之后无法执行 Gatsby Graph QL 查询。例如,如果您输入了用户输入的内容,则不能在该用例中使用 Gatsby 查询。

关于reactjs - 如何使用 gatsby 将值传递给 GraphQL 查询并使用react?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62796107/

相关文章:

javascript - 如何在reactjs中使用条件语句渲染组件?

django - 查询 GraphQL 中的枚举值

reactjs - 如何在 Gatsby 站点中保留或重新提供 React Context

react-router - Gatsby JS : integrating cubeportfolio gallery and redrawing after onRouteUpdate

javascript - 为什么 console.log() 显示 react_devtools_backend.js :4049 instead of the file and line number?

javascript - 如何在 Firebase 上托管的 React 元素中提供 Assets 路径?

javascript - $.get 中的 setState

reactjs - GatsbyJS - 如何在 GraphQL 中查询长文本内容字段

graphql - 如何在 GraphQL 中搜索字符串值

reactjs - 使用 Netlify CMS 的 Gatsby 镜像 - 字段 "image"不得有选择,因为类型 "String"没有子字段