微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Apollo Client Reactive变量-更新值后不触发重新呈现

如何解决Apollo Client Reactive变量-更新值后不触发重新呈现

我正在尝试使用反应变量:

我的缓存文件

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')
,

您可以执行以下操作:

NSDecimalNumber* decimalValue = [[NSDecimalNumber alloc] initWithDecimal:@(value).decimalValue]; // 15 x 10^-2
NSDecimalNumber* decimalMultiplier = [[NSDecimalNumber alloc] initWithDecimal: @(multiplier).decimalValue]; // 10 x 10^2
NSDecimalNumber* decimalResult = [decimalValue decimalNumberByMultiplyingBy:decimalMultiplier];
NSLog(@"%f",decimalResult.floatValue); // 15.000000
,

作为对之前答案的一个小更新,您可以使用更“传统”的 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];
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。