You need to enable JavaScript to run this app. React+Meteor环境下,如何为Apollo本地存储添加用户登录状态?
优惠活动
大模型
产品
解决方案
定价
更多

React+Meteor环境下,如何为Apollo本地存储添加用户登录状态?

Sync Meteor User State to Apollo Local Cache

要把Meteor的Meteor.userId()状态同步到Apollo本地缓存,让多个React组件能便捷访问这个状态,你可以按照以下步骤实现:

1. Define Local GraphQL Type for User State

首先在客户端添加本地GraphQL类型定义,用来描述我们要存储的用户ID状态:

const localTypeDefs = `
  type Query {
    currentUserId: String
  }
`;

这个定义告诉Apollo我们有一个本地查询字段currentUserId,用于存储当前登录用户的ID。

2. Initialize Cache with Initial User ID

创建InMemoryCache时,先写入Meteor.userId()的初始值到缓存中:

import gql from 'graphql-tag'; // 记得导入graphql-tag

const cache = new InMemoryCache();

// 初始化本地缓存的用户ID
cache.writeQuery({
  query: gql`
    query GetCurrentUserId {
      currentUserId
    }
  `,
  data: {
    currentUserId: Meteor.userId(),
  },
});

3. Track Meteor User State Changes

利用Meteor的响应式特性,通过Tracker.autorun监听用户登录/登出状态,自动更新Apollo缓存:

import { Tracker } from 'meteor/tracker'; // 导入Tracker

// 监听用户状态变化,同步到Apollo缓存
Tracker.autorun(() => {
  const userId = Meteor.userId();
  cache.writeQuery({
    query: gql`
      query GetCurrentUserId {
        currentUserId
      }
    `,
    data: {
      currentUserId: userId,
    },
  });
});

这样只要用户状态改变,缓存里的currentUserId就会自动更新,所有依赖该字段的组件都会触发重新渲染。

4. Access Local State in Components

现在你可以在任意React组件中通过useQuery获取这个本地状态:

import { useQuery } from 'react-apollo';
import gql from 'graphql-tag';

const GET_CURRENT_USER_ID = gql`
  query GetCurrentUserId {
    currentUserId
  }
`;

function UserInfoComponent() {
  const { data } = useQuery(GET_CURRENT_USER_ID);
  
  if (!data.currentUserId) {
    return <div>Please log in</div>;
  }
  
  return <div>Current User ID: {data.currentUserId}</div>;
}

5. Integrate into Your Existing Client Code

把上述修改整合到你提供的客户端代码中,最终代码如下:

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { render } from 'react-dom';
import { ApolloProvider } from 'react-apollo';
import { ApolloLink, from } from 'apollo-link';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import App from '../../../imports/ui/App/App';

const httpLink = new HttpLink({ uri: Meteor.absoluteUrl('graphql'), });

const authLink = new ApolloLink((operation, forward) => {
  const token = Accounts._storedLoginToken();
  operation.setContext(() => ({
    headers: {
      'meteor-login-token': token,
    },
  }));
  return forward(operation);
});

const cache = new InMemoryCache();

// 初始化本地缓存的用户ID
cache.writeQuery({
  query: gql`
    query GetCurrentUserId {
      currentUserId
    }
  `,
  data: {
    currentUserId: Meteor.userId(),
  },
});

// 监听用户状态变化,同步缓存
Tracker.autorun(() => {
  const userId = Meteor.userId();
  cache.writeQuery({
    query: gql`
      query GetCurrentUserId {
        currentUserId
      }
    `,
    data: {
      currentUserId: userId,
    },
  });
});

const client = new ApolloClient({
  link: from([authLink, httpLink]),
  cache,
});

const ApolloApp = () => (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

Meteor.startup(() => {
  render(<ApolloApp />, document.getElementById('app'));
});

Extra Notes

  • 如果你需要同步更复杂的用户信息(而非仅ID),可以扩展本地类型定义,比如添加currentUser字段,然后在Tracker.autorun中同步Meteor.user()的数据到缓存。
  • 确保你的Apollo依赖版本兼容,若使用@apollo/client替代react-apollo,核心逻辑不变,仅部分API调用会有细微差异。

内容的提问来源于stack exchange,提问作者Evanss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:50:06