如何 运行 在 forEach 中使用查询?

How to run useQuery inside forEach?

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

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

);

来自the rules of hooks

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

挂钩不能在循环内使用,因此您不能在 forEach 回调内使用它们。

您应该为每个仅使用一次 useQuery 挂钩的产品创建一个单独的组件。然后,您可以 map 产品和 return 每个产品的组件:

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
}

到运行通过设置refetchOnWindowFocus&启用[基于逻辑或手动多次 =17=] 属性设置为 false,然后调用方法 refetch()。示例如下。

const RefetchExample = () => {

const manualFetch = {
  refetchOnWindowFocus: false,
  enabled: false
}

const GetAssetImage = async () => {
  const {data} = await axiosInstance.get("Your API")
  return data
}

const {assetImage, refetch} = useQuery('assetImage', GetAssetImage, manualFetch)

const imageFetch = () => {
    refetch();
}
return (
   <Button onClick={imageFetch}>Refetch</Button>
)
}

export default RefetchExample