我正在玩reactQuery
的一个小演示应用程序,你可以在这回购中看到。该应用程序调用这模拟API。
我被困在一个问题上,我使用useQuery
钩子在产品API 文件中调用这个函数
export const getAllProducts = async (): Promise<Product[]> => {
const productEndPoint = 'http://localhost:5000/api/product';
const { data } = await axios.get(productEndPoint);
return data as Array<Product>;
};
然后,在我的ProductTable
组件中,我使用以下方法调用这个函数:
const { data } = useQuery('products', getAllProducts);
我发现对API的调用确实进行了,并返回了数据。但是网格中的表总是空的。
如果我调试,我看到useQuery返回的数据对象是未定义的。
web请求确实成功完成,我可以在浏览器中的“请求”下看到在“网络”选项卡中返回的数据。
我怀疑这可能是getAllProducts
的结构方式,也可能是异步等待问题,但无法完全解决。
有人能告诉我IO哪里出了问题吗?
发布于 2021-10-13 23:11:55
我已经成功地完成了这个任务。为了其他生病的人的利益,分享我的经验:
我从api函数开始做了一些小更改。将该功能更改为:
export const getAllProducts = async (): Promise<Product[]> => {
const response = await axios.get(`api/product`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
return response.data as Product[];
};
我不去构造axios
调用的响应,而是从它获取数据对象,返回为Product[]。
然后,我更改的第二件事是在我的ProductTable
组件中。在这里,我通过将调用更改为:
const { data } = useQuery<Product[], Error>('products', getAllProducts);
最后,我的新手犯了一个错误:因为我在本地主机上运行的docker容器中使用了模拟api,并使用http://localhost:5000/api/product调用它,所以我得到了众所周知的网络错误:
本地主机已被CORS策略阻塞:不存在“访问-控制-允许-原产地”头。
为了解决这个问题,我只是在packages.json文件中添加了一个属性:"proxy":"http://localhost:5000",
现在,这已经成功地允许像我所期望的那样获取数据。
发布于 2021-12-22 05:19:56
简单地使用,像这样的数据最初是未定义的,所以映射未定义的数据会给您一个错误,所以我们必须使用isLoading,如果isLoading是真的,那么在isLoading变为false之后,我们才会呈现或映射数据,那么我们就可以呈现或返回数据。
export const getAllProducts = async (): Promise<Product[]> => {
const productEndPoint = 'http://localhost:5000/api/product';
const res= await axios.get(productEndPoint);
return res.data as Array<Product>;
};
const { data:products , isLoading } = useQuery('products', getAllProducts);
if(isLoading){
return <FallBackView />
}
return (){
products.map(item => item)
}
https://stackoverflow.com/questions/69549378
复制相似问题