我正在使用两个@ apollo / react-hooks的useQuery挂钩来查询我的数据库,但是我注意到在将它们打印到控制台上时,数据是不确定的。我尝试了很多事情,无法修复。然后,我尝试切换挂钩的顺序,并注意到首先出现的挂钩总是返回正确的数据。
我已经验证了我的游乐场中的查询是正确的,并且由于它们都可以工作,但只有第一个查询可以工作。
const { loading: loadingFeaturedStores, error: errorFeaturedStore, data: featuredStoreData } = useQuery(GET_FEATURED_STORES);
const { loading: loadingStores, error: errorStore, data: normalStoreData } = useQuery(GET_STORES);
const renderStores = ({ type }: { type: string }): StoreCard | string => {
const loading = type === 'featured' ? loadingFeaturedStores : loadingStores;
const error = type === 'featured' ? errorFeaturedStore : errorStore;
if (!loading) {
return 'Loading...';
}
if (error) {
return `Error: ${error.message}`;
}
const stores = type === 'featured' ? featuredStoreData.stores : normalStoreData.stores;
const title = type === 'featured' ? 'Featured' : '';
console.log(JSON.stringify(featuredStoreData)); //returns correctly
console.log(JSON.stringify(normalStoreData)); //undefined
if (!stores) {
return null;
}
return stores.map(
(store): StoreCard => (
<div>
<h2>{title} Stores</h2>
<StoreCard
key={`store-${type}-key-${store.store_id}`}
name={store.name}
/>
</div>
)
);
};
在console.logs中,打印第一个钩子的总是返回正确的数据。因此,例如,如果我将挂钩的顺序切换为...
const { loading: loadingStores, error: errorStore, data: normalStoreData } = useQuery(GET_STORES);
const { loading: loadingFeaturedStores, error: errorFeaturedStore, data: featuredStoreData } = useQuery(GET_FEATURED_STORES);
第二个console.log将为我提供正确的数据。
先谢谢您! 我只是回过头来使用Apollo-React的工具,但想给出功能组件并尝试一下。
编辑:经过更多时间的测试,看来与加载未按预期进行有关吗?似乎总是被加载条件卡住,即使不应该。
编辑2:我将加载逻辑和数据到存储组件的映射移到了功能组件的render方法中,它的工作方式与广告中所宣传的一样。在尝试以功能组件方法呈现商店组件时,我仍然无法克服过去的加载。由于无法检测到变量加载一旦变为false时变量加载将导致的更改,React是否会重新渲染组件?
答案 0 :(得分:1)
问题是我的状况是!loading
,当应为loading
时,什么也没渲染。
不让自己感到羞耻,以防万一我的任何代码对其他人有帮助。