有没有办法在 React Context API 中使用 Gatsby 页面查询或静态查询?

Is there a way to use the Gatsby page query or static query with the React Context API?

我需要为电子商务网站创建购物车,因此所有页面都需要访问购物车信息,因此需要上下文 API。问题是 Gatsby 只会获取渲染页面或组件的信息,我似乎无法找到任何方法从未渲染的 Context 组件查询我的 Contentful 数据。我尝试了很多东西,搜索了互联网的每个角落。

有办法吗?或者有没有办法在没有上下文 API 的情况下创建购物车?请记住,我没有后端经验,因此无法创建服务器来处理该问题。

P.S。在 Context API 中使用简单的获取方法时,我最终成功了,但是当我在 Contentful 上构建项目时,它会导致环境变量出现问题,因此唯一的解决方案是公开 API让世界看到的关键 这是一个非常糟糕的解决方案。

您想要一个 Static Query,它将允许您查询所有产品数据,使其可用 client-side。我建议不要为此使用 React Context,而是推荐自定义 React Hook,它允许您在需要的地方导入数据,并让 Webpack 处理分块和加载它。

这是一个带有一些假架构的示例:

import { useStaticQuery, graphql } from "gatsby"

const useProductData = (id) => {
  const { data: { products } } = useStaticQuery(graphql`
    {
      data: allContentfulProduct {
        products: nodes {
          id
          name
          price
        }
      }
    }
  `)

  // Wee little usage nicety here to only return the relevant product
  // if an id is passed into the hook arguments.
  return id ? products.find(product => product.id === id) : products
}

const CartProduct = ({ productId }) => {
  const product = useProductData(productId)
  return (
    <div>
      {name} ${price.toFixed(2)}
    </div>
  )
}