Login.js 11 KB
import React, { Component } from "react";
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ScrollView,
  TextInput,
  KeyboardAvoidingView,
  AsyncStorage,
  Dimensions,
  Alert,
  AlertIOS,
} from "react-native";

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      phone: "",
      password: "",
      // 这个是注册用的nickname
      nickname: "",
      profession: "",
      id: "",
      registerDone: false,
      // 处于登录页面还是注册页面
      isRegister: false,
      IS_LOGIN: "",
      USER_ID: "",
      NICKNAME: "",
      PROFESSION: "",
    };
  }
  componentWillMount() {
    var _that = this;
    AsyncStorage.getItem("IS_LOGIN", (err, result) => {
      if (err) {
        console.error(err);
      }
      _that.setState({
        IS_LOGIN: result
      });
      console.log("Login页面的AsyncStorage", result);
    });
  }
  componentDidMount() {
    console.log("thisprops", this.props);
  }
  render() {
    const { navigate } = this.props.navigation;
    const { phone, password, nickname, profession } = this.state;
    return (
      <View style={styles.container}>
        <KeyboardAvoidingView 
          behavior="padding" 
          style={styles.KAVContainer}
        >
        <View>
          <Text style={styles.appName}>保护神</Text>
          {/* 手机号 */}
          <View style={styles.inputField}>
            <Image
              style={styles.icon}
              source={require("../assets/login/ic_phone.png")}
            />
            <TextInput
              style={styles.textInput}
              placeholder="请输入手机号"
              value={this.state.phone}
              onChangeText={phone => this.setState({ phone })}
              selectionColor="#1B9341"
              clearTextOnFocus={true}
              numberOfLines={1}
              clearButtonMode="always"
              keyboardType="default"
            />
          </View>
          {/* 密码 */}
          <View style={styles.inputField}>
            <Image
              style={styles.icon}
              source={require("../assets/login/ic_password2.png")}
            />
            <TextInput
              style={styles.textInput}
              placeholder="请输入密码"
              secureTextEntry={true}
              value={this.state.password}
              onChangeText={password => this.setState({ password })}
              selectionColor="#1B9341"
              clearTextOnFocus={true}
              numberOfLines={1}
              clearButtonMode="always"
              keyboardType="default"
            />
          </View>
          {/* 昵称 */}
          {this.state.isRegister ? (
            <View style={styles.inputField}>
              <Image
                style={styles.icon}
                source={require("../assets/login/ic_nickname.png")}
              />
              <TextInput
                style={styles.textInput}
                placeholder="请输入昵称"
                value={this.state.nickname}
                onChangeText={nickname => this.setState({ nickname })}
                selectionColor="#1B9341"
                clearTextOnFocus={true}
                numberOfLines={1}
                clearButtonMode="always"
                keyboardType="default"
              />
            </View>
          ) : null}
          {/* 职业 */}
          {this.state.isRegister ? (
            <View style={styles.inputField}>
              <Image
                style={styles.icon}
                source={require("../assets/login/ic_profession.png")}
              />
              <TextInput
                style={styles.textInput}
                placeholder="请输入职业"
                value={this.state.profession}
                onChangeText={profession => this.setState({ profession })}
                selectionColor="#1B9341"
                clearTextOnFocus={true}
                numberOfLines={1}
                clearButtonMode="always"
                keyboardType="default"
              />
            </View>
          ) : null}
          {/* 登录/注册 按钮  */}
          {!this.state.isRegister ? (
            <TouchableOpacity
              style={styles.confirmBtnLogin}
              onPress={() => {
                this.loginRequest();
              }}
            >
              <Text style={styles.confirmText}>登录</Text>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity
              style={[styles.confirmBtnRegister,{backgroundColor: (phone && password && nickname && profession) ? "#1B9341" : "#BBBBBB"}]}
              onPress={() => {
                this.register();
              }}
            >
              <Text style={styles.confirmText}>注册</Text>
            </TouchableOpacity>
          )}
          {/* 点击切换  不用管这里 */}
          {!this.state.isRegister ? (
            <TouchableOpacity
              style={styles.registerContaier}
              onPress={() =>
                this.setState({
                  isRegister: !this.state.isRegister,
                  phone: "",
                  password: "",
                  nickname: ""
                })}
            >
              <Text style={styles.register}>注册账号</Text>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity
              style={styles.registerContaier}
              onPress={() =>
                this.setState({
                  isRegister: !this.state.isRegister,
                  phone: "",
                  password: "",
                  nickname: ""
                })}
            >
              <Text style={styles.register}>登录</Text>
            </TouchableOpacity>
          )}
          </View>
        </KeyboardAvoidingView>
      </View>
    );
  }

  // 登录
  loginRequest() {
    let that = this,
      phone = this.state.phone,
      password = this.state.password;
    if (!/^1(3|4|5|7|8)\d{9}$/.test(phone)) {
      Alert.alert("请正确输入手机号码");
      return;
    }
    if (password === "") {
      Alert.alert("请输入密码");
      return;
    }
    let formData = new FormData();
    formData.append("phone", phone);
    formData.append("password", password);

    return fetch(`https://devpay.brae.co/test/insurance/login`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: formData
    })
      .then(resp => {
        if (resp.status === 200) {
          return resp.json();
        } else {
          console.error("something went wrong!");
        }
      })
      .then(respJson => {
        if (respJson.enmsg != "ok") {
          alert(respJson.cnmsg);
        } else {
          console.log("登录后拿到的ID和nickname",respJson.data);
          let id = JSON.stringify(respJson.data.id),
              nickname = respJson.data.nickname,
              profession = respJson.data.profession;
          AsyncStorage.multiSet(
            [["IS_LOGIN", "yes"], ["USER_ID",id], ["NICKNAME",nickname], ["PROFESSION",profession]],
            function(err) {
              if (err) {
                console.log("存储出错", err);
                return false;
              }
              AsyncStorage.multiGet(["IS_LOGIN","USER_ID","NICKNAME","PROFESSION"],(err, result) => {
                if (err) {
                  console.error(err);
                }
                console.log("点击登录后的值",result)
                that.setState({
                  IS_LOGIN: result[0][1],
                  USER_ID: (result[1][1] != null) ? result[1][1] : "",
                  NICKNAME: (result[2][1] != null) ? result[2][1] : "",
                  PROFESSION: (result[3][1] != null) ? result[3][1] : "",
                })
              })
              that.props.navigation.state.params.refreshCallback({
                IS_LOGIN: "yes",
                USER_ID: id,
                NICKNAME: nickname,
                PROFESSION: profession,
              });
              setTimeout(function () { 
                that.props.navigation.goBack();
               },0)
            }
          );
        }
      })
      .catch(err => console.error(err));
  }
  // 注册
  register() {
    let that = this,
      phone = this.state.phone,
      password = this.state.password,
      nickname = this.state.nickname,
      profession = this.state.profession,
      formData = new FormData();
    if (!phone || !password || !nickname || !profession) {
      Alert.alert("请完整填写信息");
      return false;
    }
    formData.append("phone", phone);
    formData.append("password", password);
    formData.append("nickname", nickname);
    formData.append("profession", profession);

    return fetch(`https://devpay.brae.co/test/insurance/register`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: formData
    })
      .then(resp => {
        if (resp.status === 200) {
          return resp.json();
        } else {
          console.error("something went wrong!");
        }
      })
      .then(respJson => {
        if (respJson.enmsg != "ok") {
          alert(respJson.cnmsg);
        } else {
          console.log("注册按钮返回的数据", respJson.data);
          that.setState({
            isRegister: !that.state.isRegister,
            id: respJson.data.id
          });
          // alert("注册成功!");
          Alert.alert("注册成功!")
        }
      })
      .catch(err => console.error(err));
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // paddingTop: 50,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF",
    paddingLeft: 38,
    paddingRight: 38,
    paddingBottom: 80
  },
  KAVContainer: {
    flex: 1,
    justifyContent: "center",
  },
  appName: {
    fontSize: 26,
    color: "#030303",
    alignSelf: "center",
    marginBottom: 70
  },
  inputField: {
    flexDirection: "row",
    alignItems: "center",
    borderStyle: "solid",
    borderBottomWidth: 1,
    borderColor: "#E6E6E6",
    height: 51
  },
  icon: {
    width: 11,
    height: 15,
    marginRight: 10
  },
  textInput: {
    flex: 1
  },
  helpContaier: {
    flexDirection: "row",
    justifyContent: "flex-end",
    marginTop: 10
  },
  forgetPassword: {
    color: "#999999",
    fontSize: 14
  },
  confirmBtnLogin: {
    marginTop: 30,
    width: Dimensions.get('window').width * 0.8,
    height: 45,
    backgroundColor: "#1B9341",
    borderRadius: 5,
    alignItems: "center",
    justifyContent: "center"
  },
  confirmBtnRegister: {
    marginTop: 30,
    width: Dimensions.get('window').width * 0.8,
    height: 45,
    // backgroundColor: "#BBBBBB",
    borderRadius: 5,
    alignItems: "center",
    justifyContent: "center"
  },
  confirmText: {
    color: "#fff",
    fontSize: 16
  },
  registerContaier: {
    alignItems: "center",
    justifyContent: "center"
  },
  register: {
    marginTop: 24,
    color: "#1B9341"
  }
});