Apollo 客户端:Keep/Reset 默认清除或重置存储

Apollo Client: Keep/Reset defaults on clearing or resetting store

我正在使用 apollo-link-state 在本地存储错误,但在清除缓存后出现以下错误。

我已经在 apollo 客户端配置选项中将 errors 的默认值设置为一个空数组 []

然而,在apolloClient.cache.reset()apolloClient.store.reset()之后,似乎我丢失了所有默认值,导致了这个错误:

有解决此问题的想法吗?

来自docs

Sometimes you may need to reset the store in your application, for example when a user logs out. If you call client.resetStore anywhere in your application, you will need to write your defaults to the store again. apollo-link-state exposes a writeDefaults function for you. To register your callback to Apollo Client, call client.onResetStore and pass in writeDefaults.

所以你可以这样做:

const cache = new InMemoryCache()
const link = withClientState({ cache, resolvers, defaults })

const client = new ApolloClient({
  cache,
  link,
})

client.onResetStore(stateLink.writeDefaults)

使用 Apollo 2.x,您只需执行以下操作:

cache.writeData({data : defaultData });

client.onResetStore(() => {
  cache.writeData({data : defaultData });
});

假设您在这段代码之上设置了缓存的默认数据。