首页 > 解决方案 > 为什么 Apollo 查询在存储重置后不从缓存中返回更新的值?

问题描述

我最近将Apollo本地状态添加到我的 react/next.js 网站。我正在使用 Apolloclient.writeData函数来更新缓存并useQuery提取更新。一切正常,但如果我运行 Apollo client.resetStore(),然后执行更新缓存的操作,useQuery用于获取更新值的组件将不再获取值/更新。因此,我对本地状态的更改在client.resetStore(). 我检查了缓存本身是否通过 Apollo 开发人员工具进行了更新。所以useQuery当值更新时不会以某种方式重新运行。不知道我错过了什么。

这是 Apollo 客户端设置:

import withApollo from 'next-with-apollo';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import introspectionQueryResultData from '../../fragmentTypes.json';
import { gqlTypes } from 'helpers';

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData
});

function createClient({ ctx, headers, initialState }) {
  const cache = new InMemoryCache({ fragmentMatcher });
  const client = new ApolloClient({
    credentials: 'include',
    uri: 'graphql_url',
    cache: cache.restore(initialState || {}),
    headers: {
      cookie: headers?.cookie
    },
    resolvers: {}
  });

  // initialize state
  const initialLocalState = {
    callToReview: {
      __typename: gqlTypes.CallToReviewData,
      overallRating: 0,
      openUserReviewForm: false
    }
  };

  cache.writeData({
    data: initialLocalState
  });

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

export default withApollo(createClient, { getDataFromTree: 'ssr' });

这是我的查询:

query consumptionAndCallToReview {
  consumptionMethods {
    _id
    slug
  }
  callToReview @client(always: true) {
    overallRating
    openUserReviewForm
  }
}

这是我的组件:

import React, { useEffect } from 'react'
const MyComponent = props => {
  const callToReviewData = useQuery(consumptionAndCallToReviewQuery);
  useEffect(() => {
    if (callToReviewData?.openUserReviewForm) {
      // do something...
    }
  }, [callToReviewData]);

  return (
    // ...jsx
  )
}

最后我通过以下方式重置商店:

import React, { useEffect } from 'react'
import { useApolloClient } from 'react-apollo';
const ResetComponent = props => {
  const client = useApolloClient();
  useEffect(() => {
    if (//some conditions) {
      client.stop();
      client.resetStore()
    }
  }, [callToReviewData]);

  return (
    // ...jsx
  )
}

标签: reactjsreact-apolloapollo-clientreact-state-management

解决方案


推荐阅读