import React, { createContext, useContext, useState, useEffect } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; type AuthContextType = { isLoggedIn: boolean; login: () => Promise; logout: () => Promise; }; const AuthContext = createContext(null); export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [isLoggedIn, setIsLoggedIn] = useState(false); useEffect(() => { // 检查存储的登录状态 checkLoginStatus(); }, []); const checkLoginStatus = async () => { try { const value = await AsyncStorage.getItem('isLoggedIn'); setIsLoggedIn(value === 'true'); } catch (error) { console.error('Error checking login status:', error); } }; const login = async () => { try { await AsyncStorage.setItem('isLoggedIn', 'true'); setIsLoggedIn(true); } catch (error) { console.error('Error logging in:', error); } }; const logout = async () => { try { await AsyncStorage.setItem('isLoggedIn', 'false'); setIsLoggedIn(false); } catch (error) { console.error('Error logging out:', error); } }; return ( {children} ); }; export const useAuth = () => { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used within an AuthProvider'); } return context; };