我正在使用两个 @apollo/react-hooks 的 useQuery Hook 来查询我的数据库,但我注意到将它们打印到控制台时数据未定义。我尝试了很多方法但无法修复它。然后我尝试切换钩子(Hook)的顺序,并注意到顺序第一个的钩子(Hook)总是返回正确的数据。
我已经验证了我的 Playground 中的查询是正确的,因为它们都有效,但只有第一个有效。
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中,打印第一个钩子(Hook)的总是返回正确的数据。因此,例如,如果我将钩子(Hook)的顺序切换为看起来像......
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 中的,但想尝试一下功能组件和钩子(Hook)。
编辑:经过更多时间的测试,似乎与加载未按预期工作有关?似乎总是卡在加载条件上,即使它不应该卡住。
编辑 2:我将加载逻辑和数据到存储组件的映射移至功能组件的渲染方法中,并且它的工作方式如广告中所宣传的那样。在尝试以功能组件方法渲染我的商店组件时,我仍然无法完成加载。 React 是否不会重新渲染我的组件,因为它没有检测到变量加载一旦变为 false 就会导致的变化?
最佳答案
问题是我的条件是!loading
,而它应该是loading
,这导致没有渲染任何内容。
留下这个让我自己感到羞愧,以防万一我的代码对其他人有帮助。
关于reactjs - GraphQL Apollo React Hooks 查询根据初始化顺序返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446009/