You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何识别不同层级登录用户角色(患者/医生)

React Native 登录后识别用户角色(患者/医生)的实现方案

1. 后端接口返回角色标识

登录接口校验通过后,除了返回登录凭证(如JWT Token),必须在响应体中明确返回用户角色字段,比如userRole,取值设为patient或doctor即可。

示例响应结构:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "userInfo": {
    "id": 123,
    "name": "张三",
    "userRole": "patient" // 或 "doctor"
  }
}

2. 前端持久化存储角色信息

登录成功后,把userRole和token一起存在本地存储中,推荐用RN内置的AsyncStorage,或者性能更优的第三方库MMKV,确保App重启后能快速读取角色信息。

示例代码(AsyncStorage):

import AsyncStorage from '@react-native-async-storage/async-storage';

// 登录成功后执行存储逻辑
const handleLoginSuccess = async (responseData) => {
  const { token, userInfo } = responseData;
  try {
    await AsyncStorage.multiSet([
      ['authToken', token],
      ['userRole', userInfo.userRole]
    ]);
    // 跳转到对应角色的首页
    navigateToHome(userInfo.userRole);
  } catch (e) {
    console.error('存储用户信息失败:', e);
  }
};

3. 全局状态管理(可选但推荐)

如果App多个页面需要频繁获取角色信息,用Context API或Redux维护全局状态,避免重复从本地存储读取。

示例Context实现:

// AuthContext.js
import { createContext, useContext, useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [userRole, setUserRole] = useState(null);

  useEffect(() => {
    // 初始化时从本地读取角色
    const loadUserRole = async () => {
      const role = await AsyncStorage.getItem('userRole');
      setUserRole(role);
    };
    loadUserRole();
  }, []);

  return (
    <AuthContext.Provider value={{ userRole, setUserRole }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);

在App.js中包裹根组件:

import { AuthProvider } from './AuthContext';

const App = () => {
  return (
    <AuthProvider>
      {/* 路由或根组件 */}
    </AuthProvider>
  );
};

4. 路由层面的角色判断

登录后根据角色跳转不同首页,或者在路由守卫中限制页面访问权限(比如医生页面不允许患者进入)。

示例React Navigation路由跳转:

const navigateToHome = (role) => {
  if (role === 'doctor') {
    navigation.replace('DoctorHome');
  } else {
    navigation.replace('PatientHome');
  }
};

路由守卫示例(自定义导航组件):

const ProtectedRoute = ({ component: Component, allowedRoles }) => {
  const { userRole } = useAuth();

  if (!userRole) {
    return <LoginScreen />;
  }

  if (!allowedRoles.includes(userRole)) {
    // 无权限时跳转到对应首页或提示页面
    return userRole === 'patient' ? <PatientHome /> : <DoctorHome />;
  }

  return <Component />;
};

// 使用方式
<Stack.Screen
  name="DoctorDashboard"
  component={DoctorDashboard}
  options={{ headerShown: false }}
  initialParams={{ allowedRoles: ['doctor'] }}
/>

5. 页面内的角色适配逻辑

在页面组件中,根据角色渲染不同的UI元素,比如按钮、菜单选项或功能模块。

示例条件渲染:

import { useAuth } from './AuthContext';

const HomeScreen = () => {
  const { userRole } = useAuth();

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>欢迎回来,{userRole === 'doctor' ? '医生' : '患者'}!</Text>
      {userRole === 'doctor' ? (
        <Button title="查看患者列表" onPress={() => navigation.navigate('PatientList')} />
      ) : (
        <Button title="预约挂号" onPress={() => navigation.navigate('Appointment')} />
      )}
    </View>
  );
};

注意事项

  • 敏感操作(比如医生专属接口调用)必须在后端再次校验角色,不能仅依赖前端判断,防止伪造角色信息。
  • 退出登录时要清除本地存储的userRole和token,避免残留信息导致逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:25:40