我们有一个网络应用程序。我们一直在广泛使用 Apollo + React 的 useQuery 来为用户提供无限滚动体验。我们最近意识到在第二次使用
fetchMore
后组件没有加载资产。在网络选项卡上,第一个和第二个请求不断循环。
经过一些调试,我意识到我需要在Apollo中有一个合并功能,以便我们在使用时合并数据
fetchMore
。
我更改了代码。在下面的 typePolicies 中添加了 AssetData:
export const getApolloClient = (): ApolloClient<NormalizedCacheObject> =>
new ApolloClient({
cache: new InvalidationPolicyCache({
typePolicies: {
AssetData: {
keyFields: [],
fields: {
assets: {
merge(existing = [], incoming: string[], { args }) {
return [...existing, ...incoming];
}
}
}
},
},
invalidationPolicies: {
types: {
Asset: {
timeToLive: 29 * 60 * 1000
}
}
}
}),
link: new HttpLink({ fetch })
});
这有助于打破循环。但我仍然看到,在每次 fetchMore 请求之后,都会触发对原始查询的另一个重复网络调用。这实际上搞乱了 Apollo 中的整个合并功能。我会有很多重复数据。很多人报告了类似的问题,我尝试了很多建议的解决方案 [https://github.com/apollographql/apollo-client/issues/7307][1],[https://github.com/apollographql/apollo-client /issues/7939][2], [https://github.com/apollographql/apollo-client/issues/9668][3]
但没有任何东西可以帮助我修复它。
这是我的查询:
const { loading, data, error, fetchMore, networkStatus } = useQuery<
AssetsQuery
>(assetsQuery, {
variables: {
role,
version: version,
offset: 0,
limit: 30,
region
},
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first',
});
在 apollo 团队的一个线程中提到这个问题在新版本 3.6.0 中得到解决。所以,我也将我的 apollo 版本从
3.2.0
更新到 3.6.9
,但我仍然有同样的问题。
如果您有任何建议,请告诉我
[1]:https://github.com/apollographql/apollo-client/issues/7307[2]:https://github.com/apollographql/apollo-client/issues/7939[3] :https://github.com/apollographql/apollo-client/issues/9668
尝试将@apollo/client 包更新到最新的@3.7.14。它解决了我的问题。