ReactNative 实现登录注销

登录

import React, { Component } from "react";
import { Alert, View, AsyncStorage, TextInput, Button } from "react-native";

export default class LoginPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      psw: ""
    };
  }

  onChangeName = text => {
    this.setState({ name: text });
  };

  onChangePsw = text => {
    this.setState({ psw: text });
  };

  login = async () => {
    if (this.state.name != null && this.state.name != "") {
      if (this.state.psw != null && this.state.psw != "") {
        await AsyncStorage.setItem("name", this.state.name);
        await AsyncStorage.setItem("psw", this.state.psw);

        this.props.navigation.navigate("Home");
      } else {
        Alert.alert("密码不能为空");
      }
    } else {
      Alert.alert("帐号不能为空");
    }
  };

  render() {
    return (
      
        
        
        

判断有没有存入本地

import React, { Component } from "react";
import { View, AsyncStorage, Text } from "react-native";
import {
  StackNavigator,
  createSwitchNavigator,
  createTabNavigator,
  createBottomTabNavigator
} from "react-navigation";
import HomePage from "./HomePage";
import LoginPage from "./LoginPage";

class AuthPage extends Component {
  constructor(props) {
    super(props);
    this._bootstrapAsync();
  }

  _bootstrapAsync = async () => {
    const name = await AsyncStorage.getItem("name");
    const psw = await AsyncStorage.getItem("psw");
    if (name !== null && name != "" && psw != null && psw != "") {
      this.props.navigation.navigate("Home");
    } else {
      this.props.navigation.navigate("Login");
    }
  };

  render() {
    return (
      
        qqqqqqq
      
    );
  }
}

const Switch = createSwitchNavigator({
  Auth: { screen: AuthPage },
  Home: { screen: HomePage },
  Login: { screen: LoginPage }
});

export default Switch;

注销

import React, { Component } from "react";
import { View, Text, Button, AsyncStorage } from "react-native";

export default class HomePage extends Component {
  onClick = async () => {
    await AsyncStorage.clear();
    this.props.navigation.navigate("Login");
  };
  render() {
    return (
      
        hello
        

你可能感兴趣的:(RN)