Apollo Client Reactive 变量 - 更新值后不触发重新渲染
Apollo Client Reactive variables - not trigger re render after updating the value
我正在尝试使用反应变量:
我的缓存文件:
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 的重新呈现
缓存文件(为 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')
您可以执行以下操作:
import { useReactiveVar } from "@apollo/client";
import { colorVar } from "cache"
// to read
const color = useReactiveVar(colorVar);
// to update
colorVar(your preferred color)
作为对先前答案的小更新,您可以像这样以更“传统”的反应挂钩方式进行操作:
import { useReactiveVar } from '@apollo/client'
import { colorVar } from 'cache'
const useColor = () => {
const color = useReactiveVar(colorVar);
const setColor = (color) => {
colorVar(color);
};
return [color, setColor];
}
我正在尝试使用反应变量:
我的缓存文件:
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 的重新呈现
缓存文件(为 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')
您可以执行以下操作:
import { useReactiveVar } from "@apollo/client";
import { colorVar } from "cache"
// to read
const color = useReactiveVar(colorVar);
// to update
colorVar(your preferred color)
作为对先前答案的小更新,您可以像这样以更“传统”的反应挂钩方式进行操作:
import { useReactiveVar } from '@apollo/client'
import { colorVar } from 'cache'
const useColor = () => {
const color = useReactiveVar(colorVar);
const setColor = (color) => {
colorVar(color);
};
return [color, setColor];
}