在React Native中实现身份验证流通常涉及以下几个步骤:
AsyncStorage
或SecureStore
。react-navigation
的navigation.navigate
)来确保只有经过身份验证的用户才能访问受保护的页面。以下是一个简单的示例,展示了如何在React Native中实现这些步骤:
import React, { useState } from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const LoginScreen = ({ navigation }) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async () => {
try {
// 模拟登录请求
const response = await fetch('https://your-api-endpoint.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (data.token) {
await AsyncStorage.setItem('userToken', data.token);
navigation.navigate('Home');
} else {
Alert.alert('Login Failed', 'Invalid credentials');
}
} catch (error) {
console.error(error);
Alert.alert('Error', 'Failed to login');
}
};
return (
<View>
<TextInput
placeholder="Username"
value={username}
onChangeText={setUsername}
/>
<TextInput
placeholder="Password"
secureTextEntry
value={password}
onChangeText={setPassword}
/>
<Button title="Login" onPress={handleLogin} />
</View>
);
};
export default LoginScreen;
在上面的代码中,我们使用了AsyncStorage
来存储令牌:
await AsyncStorage.setItem('userToken', data.token);
使用react-navigation
来保护路由:
import React, { useEffect } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import AsyncStorage from '@react-native-async-storage/async-storage';
import LoginScreen from './LoginScreen';
import HomeScreen from './HomeScreen';
const Stack = createStackNavigator();
const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const checkAuth = async () => {
const token = await AsyncStorage.getItem('userToken');
if (token) {
setIsAuthenticated(true);
}
};
checkAuth();
}, []);
return (
<NavigationContainer>
<Stack.Navigator initialRouteName={isAuthenticated ? 'Home' : 'Login'}>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
如果需要刷新令牌,可以在HomeScreen
中实现:
import React, { useEffect } from 'react';
import { View, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const HomeScreen = ({ navigation }) => {
const refreshTokens = async () => {
try {
// 模拟刷新令牌请求
const response = await fetch('https://your-api-endpoint.com/refresh-token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
if (data.token) {
await AsyncStorage.setItem('userToken', data.token);
} else {
Alert.alert('Token Refresh Failed', 'Failed to refresh token');
}
} catch (error) {
console.error(error);
Alert.alert('Error', 'Failed to refresh token');
}
};
useEffect(() => {
const interval = setInterval(refreshTokens, 60000); // 每分钟刷新一次
return () => clearInterval(interval);
}, []);
return (
<View>
<Button title="Logout" onPress={() => navigation.navigate('Login')} />
</View>
);
};
export default HomeScreen;
在HomeScreen
中添加登出功能:
const handleLogout = async () => {
await AsyncStorage.removeItem('userToken');
navigation.navigate('Login');
};
return (
<View>
<Button title="Logout" onPress={handleLogout} />
</View>
);
领取专属 10元无门槛券
手把手带您无忧上云