我会在这个用例中使用 Apollo 的useReactiveVar钩子。从文档
With the useReactiveVar hook, React components can also include reactive variable values in their state directly, without wrapping them in a query.
这有几个部分,所以我在下面草拟了一个解决方案,它为所有部分提供了导入声明和从依赖项开始的可能实现
import React, { useEffect, useState, useMemo } from 'react';
import { useReactiveVar, makeVar, useLazyQuery, InMemoryCache } from "@apollo/client";
制作阿波罗缓存变量
export const dataWillUpdate = {
// some nice flat schema data object,
niceFlatSchemaData: {}
};
const dataWillUpdateVar = makeVar(dataWillUpdate);
const component = () => {
// make the reactive apollo variable
const dataWillUpdateVarReactive = useReactiveVar(dataWillUpdateVar);
// memo the niceFlatSchemaData data object
const niceFlatSchemaData = useMemo(() => userProfileVarReactive.niceFlatSchemaData, [
dataWillUpdateVarReactive.niceFlatSchemaData,
]);
// see 2 for lazy queries
const [ getData, { data, loading, error: loadRolesError} ] = useLazyQuery();
useEffect(() => {
// will update here when change to niceFlatSchemaData
// so run query here
getData({variables:{input:{
// nice flat input object for the gql
}}})
}, [niceFlatSchemaData])
useEffect(() => {
// will update here when quer calls back
// state changes for render
}, [data])
}
需要在 apollo 缓存中配置变量
const globalCache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
dataWillUpdate: {
read() {
return dataWillUpdateVar();
},
},
},
},
},
});
[1] useReactiveVar
[2]惰性查询