【问题标题】:How do I initialize a variable in Apollo Client 3如何在 Apollo Client 3 中初始化变量
【发布时间】:2020-09-14 14:25:08
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: react-apollo apollo-client


    【解决方案1】:

    您可以在 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());
    

    【讨论】:

    • 我想弄清楚的相关内容。我想使用反应变量作为状态管理,并希望从我将从 graphql 服务器获取的一些数据中初始化变量。有什么推荐的方法吗?
    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 2019-05-17
    • 2019-12-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    相关资源
    最近更新 更多