【问题标题】:GraphQL Apollo React Hooks queries return null depending on order of initializationGraphQL Apollo React Hooks 查询根据初始化顺序返回 null
【发布时间】:2019-12-18 03:17:34
【问题描述】:

我正在使用两个 @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:我将加载逻辑和数据到 store 组件的映射移到了功能组件的 render 方法中,它的工作就像宣传的那样。在尝试以功能组件方法呈现我的商店组件时,我仍然无法通过加载。 react 没有重新渲染我的组件,因为它没有检测到变量加载一旦变为 false 将导致的变化?

【问题讨论】:

    标签: reactjs graphql apollo react-hooks react-apollo-hooks


    【解决方案1】:

    问题是我的条件是!loading,而它应该是loading,这导致没有任何渲染。

    留下这件事让我自己感到羞耻,以防我的任何代码对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2019-06-14
      • 2020-01-07
      • 2019-08-26
      • 2020-01-15
      • 2021-01-15
      • 2017-10-06
      • 2021-08-18
      相关资源
      最近更新 更多