[英]how to prevent other useQuery run in one component for React-Query
[英]How to run useQuery inside forEach?
我有循环 - forEach - 为数组的每个元素找到 productId 。 我想使用 apollo 查询通过 productId 获取我的数据库。 怎么做?
products.forEach(({ productId, quantity }) =>
// fetch by 'productId'
);
从钩子的规则:
不要在循环、条件或嵌套函数中调用 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
}
通过将refetchOnWindowFocus和enable属性设置为 false 然后调用方法refetch()来基于逻辑或手动多次运行 useQuery 。 示例如下。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.