React-Native强制身份认证
路由配置
import { createSwitchNavigator } from "react-navigation";
import Home from "./Home";
import Login from "./Login";
import Auth from "./Auth";
const Route = createSwitchNavigator(
{
Auth: Auth,
Home: Home,
Login: Login
},
{
initialRouteName: "Auth"
}
);
export default Route;
Auth文件代码
import React, { Component } from "react";
import { Platform, StyleSheet, Text, View, AsyncStorage } from "react-native";
export default class Auth extends Component {
constructor(props) {
super(props);
this._bootstrapAsync();
}
//判断登录认证状态:true:Home false:Login
_bootstrapAsync = async () => {
const name = await AsyncStorage.getItem("name");
const psw = await AsyncStorage.getItem("psw");
if (name && name.length >= 6) {
if (psw && psw.length >= 6) {
this.props.navigation.navigate("Home");
} else {
this.props.navigation.navigate("Login");
}
} else {
this.props.navigation.navigate("Login");
}
// const userToken = await AsyncStorage.getItem("userToken");
// this.props.navigation.navigate(userToken ? "App" : "Auth");
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>登陆失败</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
}
});
Home文件代码解析
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
AsyncStorage,
Button
} from "react-native";
export default class Home extends Component {
_signOutAsync = async () => {
await AsyncStorage.clear(); //清空
this.props.navigation.navigate("Login");
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>登陆成功</Text>
<Button title="注销" onPress={this._signOutAsync} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
}
});
Login代码解析
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
AsyncStorage,
Button,
TextInput
} from "react-native";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
pass: ""
};
}
ChangeText = text => {
this.setState({
name: text
});
};
ChangePass = text => {
this.setState({
pass: text
});
};
_signInAsync = async () => {
await AsyncStorage.setItem("name", this.state.name);
await AsyncStorage.setItem("psw", this.state.pass);
this.props.navigation.navigate("Home");
};
render() {
return (
<View style={styles.container}>
<TextInput
style={{ width: 200 }}
placeholder="请输入账号"
onChangeText={this.ChangeText}
/>
<TextInput
style={{ width: 200 }}
placeholder="请输入密码"
onChangeText={this.ChangePass}
/>
<Button title="登录" onPress={this._signInAsync} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
}
});