javascript - 通过特定查询或突变重置缓存

标签 javascript react-native caching graphql react-apollo

我想使用 react-apollo 的客户端从键或查询中重置部分缓存,而不是使用 client.resetStore() 清除整个缓存。

例子:

import { withApollo } from "react-apollo";
import { compose } from "recompose";
import MyComponent from "./MyComponent";

const cleanEspecificCache = ({ client }) => () =>{
  // What i do here?
}

const enhance = compose(
 withApollo,
 withHandlers({cleanEspecificCache})
)

export default enhance(MyComponent);

我该怎么做才能让它发挥作用?谢谢!

最佳答案

根据这个问题,目前不支持部分 Apollo 缓存清除: https://github.com/apollographql/apollo-feature-requests/issues/4

您可以使用 fechPolicy: 'network-only' 完全不缓存特定查询:

const enhance = compose(
  graphql(
    gql`{
      food {
        id
        name
      }
    }`,
    {
      options: { fetchPolicy: 'network-only' },
    }
  ),
  ...
);

export default enhance(MyComponent);

如果您想深入兔子洞并立即找到解决方案,您可以尝试https://github.com/sysgears/apollo-cache-router 它可以将您的缓存拆分为两个或更多个缓存,然后您可以单独重置这些缓存:

import { InMemoryCache } from 'apollo-cache-inmemory';
import ApolloCacheRouter from 'apollo-cache-router';
import { hasDirectives } from 'apollo-utilities';

const generalCache = new InMemoryCache();
const specialCache = new InMemoryCache();
const cache = ApolloCacheRouter.override(
  ApolloCacheRouter.route([generalCache, specialCache], document => {
    if (hasDirectives(['special'], document)) {
      // Pass all queries marked with @special into specialCache
      return [specialCache];
    } else {
      // Pass all the other queries to generalCache
      return [generalCache];
    }
  })
);

每当您想重置 specialCache 时,请在代码中调用 specialCache.reset()

关于javascript - 通过特定查询或突变重置缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51485713/

相关文章:

javascript - 检查表单中输入元素更改的方法

javascript - d3 javascript 命名或引用组

react-native - 使用 adb logcat : no matches found: *:S 无法在 react-native 应用程序中查看 Android 日志

react-native - 如何通过在 React Native 中点击模态主体来隐藏模态

删除记录后PHP页面不会自动重新加载?

linux - Unix 和 Linux 上应用程序/脚本缓存文件的正确位置是什么?

JavaScript URL 解码功能

javascript - 如何在highstock中更改股票图表中测量工具的背景颜色?

javascript - 如何在 React 中渲染对象列表

algorithm - 较大的 block 缓存大小还是较小的 block 缓存是最佳选择?