React-Native 身份认证 不强制登陆代码解析
配置路由器
import { createSwitchNavigator } from "react-navigation";
import My from "./My";
import Login from "./Login";
const Route2 = createSwitchNavigator({
My: My,
Login: Login
});
export default Route2;
登陆页面设置
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
TextInput,
Button,
AsyncStorage
} from "react-native";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
}
ChangeText = text => {
this.setState({
value: text
});
};
_signInAsync = async () => {
await AsyncStorage.setItem("userToken", this.state.value);
this.props.navigation.navigate("My");
};
render() {
return (
<View style={styles.container}>
<TextInput
style={{ width: "100%" }}
placeholder="请输入您的账号"
onChangeText={this.ChangeText}
/>
<TextInput style={{ width: "100%" }} placeholder="请输入您的密码" />
<Button onPress={this._signInAsync} title="登陆" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
welcome: {
fontSize: 20,
textAlign: "center",
margin: 10
}
});
登陆成功页面显示
import React, { Component } from "react";
import {
Image,
StyleSheet,
AsyncStorage,
Text,
View,
Button
} from "react-native";
export default class My extends Component {
constructor(props) {
super(props);
this.state = {
value: false,
name: ""
};
}
componentDidMount() {
this._bootstrapAsync();
}
_bootstrapAsync = async () => {
const userToken = await AsyncStorage.getItem("userToken");
if (userToken && userToken.length > 0) {
this.setState({
value: true,
name: userToken
});
} else {
this.setState({
value: false,
name: ""
});
}
};
Zhuxiao = async () => {
await AsyncStorage.clear();
this.setState({
value: false,
name: ""
});
};
render() {
return (
<View style={styles.container}>
{this.state.value ? (
<View style={{ marginBottom: 20 }}>
<View style={{ flexDirection: "row" }}>
<Image
style={{ width: 60, height: 60, borderRadius: 80 }}
source={require("./../../lzj.png")}
/>
<Text style={{ marginLeft: 15, fontSize: 20, marginTop: 15 }}>
{this.state.name}
</Text>
</View>
</View>
) : (
<View>
<View style={{ flexDirection: "row" }}>
<Image
style={{ width: 60, height: 60, borderRadius: 80 }}
source={require("./../../e5.png")}
/>
<Text
style={{ marginLeft: 15, fontSize: 20, marginTop: 15 }}
onPress={() => {
this.props.navigation.navigate("Login");
}}
>
未登录
</Text>
</View>
</View>
)}
{this.state.value && (
<Button
style={{ marginTop: 20 }}
onPress={this.Zhuxiao}
title="注销"
/>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
welcome: {
fontSize: 20,
textAlign: "center",
margin: 10
}
});
其中图片是本人放置,如复制代码可以更改图片路径