如何在 forEach 中运行 useQuery?

Tom*_*asz 3 javascript hook apollo graphql

我有循环 - forEach - 为数组的每个元素找到 productId 。我想使用 apollo 查询通过 productId 获取我的数据库。怎么做?

products.forEach(({ productId, quantity }) =>
    // fetch by 'productId'

);
Run Code Online (Sandbox Code Playgroud)

lee*_*len 7

如果你想执行多个调用,useQuery那么你不能在 forEach、map 等中执行此操作。你需要使用useQueries例如

function Products({ productIds }) {
  const productQueries = useQueries({
    queries: productIds.map(productId => {
      return {
        queryKey: ['productById', productId],
        queryFn: () => fetchProductById(productId),
      }
    })
  })
Run Code Online (Sandbox Code Playgroud)

示例取自:https://tanstack.com/query/v4/docs/guides/parallel-queries


Dan*_*den 5

钩子的规则

不要在循环、条件或嵌套函数中调用 Hook。相反,始终在 React 函数的顶层使用 Hook。通过遵循此规则,您可以确保每次渲染组件时以相同的顺序调用 Hook。

钩子不能在循环中使用,所以你不能在forEach回调中使用它们。

您应该为每个只使用useQuery一次钩子的产品创建一个单独的组件。然后map,您可以遍历产品并为每个产品返回组件:

const YourComponent = () => {
  ...
  return products.map(({ productId, quantity }) => (
    <Product key={productId} productId={productId} quantity={quantity} />
  ))
}

const Product = () => {
  const { data, error, loading } = useQuery(...)
  // render your data accordingly
}
Run Code Online (Sandbox Code Playgroud)