【问题标题】:How to restore cache to its initial state如何将缓存恢复到初始状态
【发布时间】:2019-01-15 04:14:43
【问题描述】:

我使用 SSR 为来自服务器的初始状态的缓存补充水分

const cache = new InMemoryCache().restore(window.__APOLLO_STATE__)

稍后发生一些突变,我需要将缓存硬重置为其初始状态。我天真地试图将初始存储保持在组件状态并将其传递给client.restore

componentDidMount () {
  this.setState({
    initState: this.props.client.extract()
  })
}

// When I need to reset, I'd call this method...
handleCacheReset () {
  this.props.client.restore( this.state.initState )
}

但它没有用。由于我也在使用apollo-link-state,所以我想如果我将缓存数据保留为默认值,也许我可以在调用client.resetStore时编写它们

const cache = new InMemoryCache().restore(window.__APOLLO_STATE__)
const link = withClientState({ cache })
const client = new ApolloClient({
  link, cache,
  defaults: cache.data.data
})
client.onResetStore(link.writeDefaults)

// ...when it's time to reset the store
client.resetStore()

但我只收到Missing field ... in {} 错误,并且没有数据写入存储。更糟糕的是,我不能使用client.writeData,因为我只有初始的window.__APOLLO_STATE__。如果我可以读取整个缓存数据,那么它可能是合理的,但似乎没有readData 方法。

有没有办法以编程方式将缓存恢复到原始状态?

到目前为止,我看到的唯一解决方法是重新创建整个 ApolloClient 并强制重新渲染树,这既昂贵又低效。想法?

附:在GitHub 上问过这个问题,但他们没有回答就关闭了。

【问题讨论】:

  • 它曾经是client 上的readFragmentreadQuery 方法。你检查了吗?

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


【解决方案1】:

this.props.client.extract() 直接返回缓存对象而不是副本: https://github.com/apollographql/apollo-client/blob/master/packages/apollo-cache-inmemory/src/depTrackingCache.ts#L23

如果你想保持原来的状态,你可以这样做:

initState: {...this.props.client.extract()}

【讨论】:

    【解决方案2】:

    这是在网络还是移动设备上?我自己无法解决这个问题,但在考虑 apollo-cache-persist 时,理论上您可以将缓存的状态保存到本地存储并在以后将它们恢复到缓存中。

    【讨论】:

    • 网络。我会试试apollo-cache-persist
    猜你喜欢
    • 1970-01-01
    • 2015-07-11
    • 2013-05-19
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    相关资源
    最近更新 更多