1. 程式人生 > >ReactNative 實現登入登出

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 (
      <View style={{ flex: 1 }}>
        <TextInput
          placeholder="請輸入帳號..."
          onChangeText={this.onChangeName}
        />
        <TextInput
          placeholder="請輸入密碼..."
          onChangeText={this.onChangePsw}
        />
        <Button title="登入" onPress={this.login} />
      </View>
    );
  }
}

判斷有沒有存入本地

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 (
      <View style={{ flex: 1 }}>
        <Text>qqqqqqq</Text>
      </View>
    );
  }
}

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 (
      <View style={{ flex: 1 }}>
        <Text style={{ textAlign: "center" }}>hello</Text>
        <Button title="登出" onPress={this.onClick} />
      </View>
    );
  }
}