reactjs - 为什么 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
)
}
解决方案
推荐阅读
- php - Wordpress - 显示指向当前页面的路径的页面
- java - 使用 Struts 的 JQuery.ajax 错误 400 错误请求
- mongodb - symfony4 与教义-odm:如何在聚合构建器中添加一个或多个组
- java - 创建大小未知的数组?
- dns - 仅使用 DNS 重写 URL
- dart - Bloc 模式不会在屏幕上显示新添加的用户到 sqflite
- html - Bootstrap 4 列和行产生不需要的填充
- java - Spark 作业问题 [java.lang.VerifyError: class com.fasterxml.jackson.module.scala.ser.ScalaIteratorSerializer 覆盖 final 方法 withResolved]
- google-analytics - BigQuery:过滤表后出现意外结果
- oauth - 在 Datapower/API Connect [OAuth2] 中禁用一次刷新令牌?