【问题标题】:Avoid multiple network calls with hooks and Apollo使用 hooks 和 Apollo 避免多次网络调用
【发布时间】:2022-08-09 21:24:50
【问题描述】:

我有一个可以进行 Graphql 调用的钩子

export const useGetStuff = (options?: QueryHookOptions<GetStuffResponse, GetStuffQueryArgs>) => {
    const [stuffId] = useStuffId();

    return useQuery<GetStuffResponse, GetStuffQueryArgs>(getStuff, {
        variables: { stuffId },
        notifyOnNetworkStatusChange: true,
        skip: !stuffId,
        ssr: false,
        ...options,
    });
};

我在另一个钩子中使用这个钩子

const useCustomHook = () => {
    // some unrelated stuff
    const { data: stuffData, loading } = useGetStuff();
   
    // do logic with stuffData and other unrelated stuff

    return { someProperty };
    
}

在某些组件中,我同时使用useGetStuffuseCustomHook

const MyComponent = () => {
    const { someProperty } = useCustomHook();
    const { data ,loading } = useGetStuff();

    // stuff
    
}

此实现导致getStuff 查询被调用两次(两次网络调用)。

有没有一种简单的方法可以避免这种情况,而不必仅将useGetStuff 保留在自定义挂钩中,因为后者不必返回stuffData

  • 你调用 useGetStuff 两次,所以它运行了两次..
  • 是的,我正在寻找避免这种情况的方法,或者如果我可以调用该钩子两次但只调用一次网络调用会更好。
  • 为什么不直接返回 useGetStuff 在 useCustomHook 中生成的数据?

标签: javascript reactjs graphql apollo react-apollo


【解决方案1】:

你犯了一个非常基本的错误,你实际上在每个钩子调用上都返回了一个新对象,所以 React 不知道什么时候停止。虽然useGetStuff 返回整个对象,所以它应该不是问题,第二个钩子返回一个新的{ someProperty }; 对象,每个component 调用都有新的引用。

解决这个问题的方法是实际记忆对象:

const useCustomHook = () => {
    // some unrelated stuff
    const { data: stuffData, loading } = useGetStuff();
   
    // do logic with stuffData and other unrelated stuff

    return useMemo(() => {
        return { someProperty };
    }, [theThingThatShouldTriggerNewObjectCreation]);
}

【讨论】:

    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2012-09-05
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多