【问题标题】:Apollo Client Reactive variables - not trigger re render after updating the valueApollo 客户端反应变量 - 更新值后不触发重新渲染
【发布时间】:2021-01-23 04:16:23
【问题描述】:
我正在尝试使用反应变量:
我的缓存文件:
import { makeVar } from "@apollo/client"
export const colorVar = makeVar('red')
文件A(更新值):
import { colorVar } from "cache"
colorVar('green')
文件 B(读取值并在文件 A 中更新值后重新渲染):
import { colorVar } from "cache"
console.log(colorVar())
文件A中的更新动作不会触发文件B的重新渲染
【问题讨论】:
标签:
reactjs
apollo-client
reactive-variable
【解决方案1】:
缓存文件(为 ApolloClient 使用该缓存):
export const cache: InMemoryCache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
getColor()
return colorVar();
}
}
}
}
});
export const colorVar = cache.makeVar('red')
更新变量(文件 A):
import { colorVar } from "cache"
colorVar('green')
读取变量(文件B):
const GET_COLOR_Q = gql`
query readColor {
getColor @client
}
`;
const { data } = useQuery(GET_COLOR_Q);
console.log(data?.getColor)
更新:在 Apollo Client 3.2.0 中,您可以使用 useReactiveVar 挂钩来获取数据(文件 B):
import { useReactiveVar } from '@apollo/client'
import { colorVar } from "cache"
// read
const color = useReactiveVar(colorVar)
console.log(color)
// write
colorVar('green')
【解决方案2】:
您可以执行以下操作:
import { useReactiveVar } from "@apollo/client";
import { colorVar } from "cache"
// to read
const color = useReactiveVar(colorVar);
// to update
colorVar(your preferred color)
【解决方案3】:
作为对先前答案的一个小更新,您可以像这样以更“传统”的 react-hooks 方式进行操作:
import { useReactiveVar } from '@apollo/client'
import { colorVar } from 'cache'
const useColor = () => {
const color = useReactiveVar(colorVar);
const setColor = (color) => {
colorVar(color);
};
return [color, setColor];
}