当前位置: 首页 > news >正文

Expo+React Native实现鉴权

一、引入相关依赖

npm i @reduxjs/toolkit  react-redux expo-secure-store axios
依赖 作用
@reduxjs/toolkit 简化 Redux 开发的官方工具包,提供标准化的 Redux 最佳实践
react-redux 连接 React 组件和 Redux Store 的官方绑定库
expo-secure-store 安全的、异步的键值存储系统
axios 网络请求

二、实现流程

1、通过axios获取token
2、通过redux记录登录标志和token,同时将数据保存到本地存储中
3、定义一个组件AuthInitializer,用于初始化时从本地缓存中更新redux数据

三、各种文件配置

@/utils/auth.js

import * as SecureStore from 'expo-secure-store';/*** 保存认证信息到本地存储*/
export const saveAuthInfo = async (isLogin, token = '') => {try {await SecureStore.setItemAsync('auth', JSON.stringify({isLogin,token}));} catch (error) {console.error('Error saving auth info:', error);}
};/*** 从本地存储获取认证信息*/
export const getAuthInfo = async () => {try {const storedAuth = await SecureStore.getItemAsync('auth');if (storedAuth) {return JSON.parse(storedAuth);}} catch (error) {console.error('Error getting auth info:', error);}return null;
};/*** 清除本地认证信息*/
export const clearAuthInfo = async () => {try {await SecureStore.deleteItemAsync('auth');} catch (error) {console.error('Error clearing auth info:', error);}
};

@/store/slices/authSlice.js

import {createSlice} from '@reduxjs/toolkit'
import {saveAuthInfo, clearAuthInfo} from '@/utils/auth';const authSlice = createSlice({name: 'auth',initialState: {isLogin: false,token: '',},reducers: {login(state, {payload: {isLogin, token = ''}}) {state.isLogin = isLogin;state.token = token;},logout(state) {state.isLogin = false;state.token = '';}}
})// 创建中间件来处理本地存储
export const authMiddleware = (store) => (next) => async (action) => {const result = next(action);const state = store.getState();try {if (state.auth.isLogin) {// 登录时将状态以及token保存到本地存储中await saveAuthInfo(state.auth);} else {// 登出时清除本地存储await clearAuthInfo();}} catch (error) {console.error('Error saving auth state to secure store:', error);}return result;
};export const {login, logout} = authSlice.actions;
export default authSlice.reducer;

@/store/index.js

import {configureStore} from '@reduxjs/toolkit'
import authSlice, {authMiddleware} from '@/store/slices/authSlice'const store = configureStore({reducer: {auth: authSlice},middleware: (getDefaultMiddleware) =>getDefaultMiddleware().concat(authMiddleware)
})export default store

src/app/(auth)/_layout.js

const { isLogin } = useSelector((state) => state.auth);// 认证完成后重定向到首页
if (isLogin) {return <Redirect href='/(auth)/(tabs)'/>
}

@/components/AuthInitializer

import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import {getAuthInfo} from "@/utils/auth";
import { login,logout } from '@/store/slices/authSlice';
import { View } from 'react-native';const AuthInitializer = ({ children }) => {const dispatch = useDispatch();const [isLoading, setIsLoading] = useState(true);useEffect(() => {const initializeAuth = async () => {try {const storedAuth = await getAuthInfo('auth');if (storedAuth) {dispatch(login(storedAuth));} else {// 没有存储的认证信息,标记为已检查dispatch(logout());}} catch (error) {console.error('Error initializing auth state:', error);dispatch(logout());} finally {setIsLoading(false);}};initializeAuth();}, [dispatch]);if (isLoading) {// 在认证状态加载完成前显示加载指示器return <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}/>}return children;
};export default AuthInitializer;

src/app/_layout.js

import {Slot} from 'expo-router';
import '@/global.css'
import {Provider} from 'react-redux';
import store from "@/store";
import AuthInitializer from "@/components/AuthInitializer";export default function Layout() {return <Provider store={store}><AuthInitializer><Slot/></AuthInitializer></Provider>
}
http://www.jsqmd.com/news/295007/

相关文章:

  • Java毕设项目推荐-基于springboot的养老院管理系统的设计与实现基于SpringBoot+Vue的养老院管理系统【附源码+文档,调试定制服务】
  • Java毕设项目推荐-基于Springboot的幼儿园综合管理系统基于springboot的幼儿园管理系统【附源码+文档,调试定制服务】
  • 随笔-无具体内容
  • 吐血推荐!继续教育10款AI论文平台测评与推荐
  • 2026.1.24 作业 - # P14317 「ALFR Round 11」A 浴眼盯真 (dingzhen)
  • 深度测评专科生必用8款一键生成论文工具:开题报告文献综述全攻略
  • 这份AI支持的开题报告模板,能帮助你在学术研究中节省宝贵时间
  • 【AI经典论文解读】《High-Resolution Image Synthesis with Latent Diffusion Models(基于潜在扩散模型的高分辨率图像合成)》论文深度解读
  • 学术研究的起点很关键,AI优化的开题报告模板能帮你快速上手
  • 风电传动系统故障特征分析与诊断【附代码】
  • 收益可视化营销:如何用“55万收益案例”吸引创业者?
  • 油动机液压系统异常检测与轻量化故障诊断【附代码】
  • 计算机Java毕设实战-基于springboot+vue好生活养老院管理系统基于springboot的养老院管理系统的设计与实现【完整源码+LW+部署说明+演示视频,全bao一条龙等】
  • Java毕设项目:基于springboot的养老院管理系统的设计与实现(源码+文档,讲解、调试运行,定制等)
  • 【课程设计/毕业设计】基于SpringBoot+Vue的养老院管理系统基于springboot的养老院管理系统的设计与实现【附源码、数据库、万字文档】
  • Java计算机毕设之基于springboot的养老院管理系统的设计与实现基于SpringBoot的养老中心管理系统设计与实现(完整前后端代码+说明文档+LW,调试定制等)
  • 【毕业设计】基于springboot的养老院管理系统的设计与实现(源码+文档+远程调试,全bao定制等)
  • 设计模式之:简单工厂模式 - 教程
  • webtest / project AI / aitest / aiceshi / Dify
  • java中输入输出的优化
  • 全网最全研究生必备AI论文工具TOP8测评
  • 利用AI技术自动生成的开题报告模板,让学术写作的第一步更轻松
  • 学术写作的第一步不再复杂,AI工具助你高效完善开题报告模板
  • 借助AI工具的强大功能,轻松生成一份高质量的开题报告模板
  • 这份由AI辅助设计的开题报告模板,能显著提升你的学术写作效率
  • 学术写作的第一步至关重要,AI工具助你优化开题报告模板的结构
  • 小程序基于前后端分离的外卖点餐骑手送餐系统
  • 通过AI智能分析,这份开题报告模板能帮你快速完成学术论文的初稿
  • 微信小程序二手物品交易平台开发
  • 微信小程序的—宠物售卖商店看病预约业务系统