首页 > 解决方案 > 如何在 Apollo Client 3 中初始化变量

问题描述

嘿,我正在尝试学习 Apollo Client v3,但我无法完全理解文档和新的本地状态管理。

我想要一个状态,它记得上次使用的月份和年份。当我创建一个新的 ApolloClient 时,这就是我在旧 Apollo 中所拥有的

clientState: {
  defaults: {
    currentMonth: 8,
    currentYear: 2020,
  },
},

所以试图理解新文档这就是我尝试过的

const cache = new InMemoryCache({
    typePolicies: {
        clientState: {
            fields: {
                month: 8,
                year: 2020,
            },
        },
    },
});

但没有运气。我因为不理解文档而感到非常愚蠢,但很难找到任何与我的问题相似的东西。现在我真的很接近切换到 Redux 但仍然希望有一个解决方案。

标签: react-apolloapollo-client

解决方案


您可以在 Apollo Client 3 中使用反应变量。

https://www.apollographql.com/docs/react/local-state/reactive-variables/#:~:text=New%20in%20Apollo%20Client%203,application%20without%20using%20GraphQL%20syntax

对于您的示例:

定义

import { makeVar } from '@apollo/client';

export const currentMonth = makeVar(8);
export const currentYear = makeVar(2020);

得到

import { currentMonth, currentYear } from "./yourPath/yourFile";

// Output: 8
console.log(currentMonth());

// Output: 2020
console.log(currentYear());

import { currentMonth, currentYear } from "./yourPath/yourFile";

currentMonth(9);
    
// Output: 9
console.log(currentMonth());
    
currentYear(2021);
    
// Output: 2021
console.log(currentYear());

推荐阅读