(十)ReactNative类android-Sharepreference和ios-NSDefaultUser的数据持久化存储

本文参考:http://www.jb51.net/article/94164.htm

AsyncStorage存储类似Android中的sharedpreference存储或者IOS中的NSDefaultUser不过ReactNative中的AsyncStorage只能存储字符串类型

常用方法:

getItem(key:string,callback?:?(error:?Error,result:?string)=>void) 静态方法,该通过key字段来进行查询存储的数据,把该结果值作为参数传入第二个callback方法。如果发生错误,会把Error对象传入callback方法。该方法最终返回一个Promise对象

setItem(key:string,value:string,callback?:?(error:?Error)=>void) 静态方法,该根据key字段设置value内容,完成之后进行回调callback方法。如果发生错误会把Error对象传入callback方法中。该方法返回一个Promise对象。

removeItem(key:string,callback?:?(error:?Error)=>void) 静态方法,根据key进行删除值,成功之后进行回调callback方法。如果发生错误会把Error对象传入callback方法中。该方法返回一个Promise对象

根据以上做一个已登录的判断:

/*
 * @Describe: 登录
 * @Author: lf
 * @Date: 2017-04-25 14:16:22
 * @Last Modified by: lf
 * @Last Modified time: 2017-04-26 11:35:56
 */
import React, {Component} from 'react';

import {
  Text,
  View,
  ListView,
  Image,
  TouchableHighlight,
  Navigator,
  TouchableOpacity,
  ToastAndroid,
  TextInput,
  Button,
  Switch,
  AsyncStorage
} from 'react-native';

import styles from '../../styles/login/LoginStyle';
import BaseComponent from '../BaseComponent';
import TitleBarView from '../../custom_view/TitleBarView';
import MyNavigator from '../Navigator';

const Realm = require('realm');

export default class LoginComponent extends BaseComponent {

  constructor(props) {
    super(props);
    this.state = {
      userName: '',
      userPwd: '',
      isMemoryPwd: true, //是否记住密码
    };

    const user = {
      name: 'user',
      properties: {
        id: 'int',
        name: 'string',
        pwd: 'string'
      }
    };

    //初始化Realm
    realm = new Realm({schema: [user]});

    // 数据插入 realm.write(() => {   realm.create('user', {     id: 1,     name:
    // 'zhangsan',     pwd: 'SB001'   });   realm.create('user', {     id: 2, name:
    // 'lisi',     pwd: 'SB002'   });   realm.create('user', {     id: 3, name:
    // 'wangwu',     pwd: 'SB003'   });   realm.create('user', {     id: 4,  name:
    // 'ceshi',     pwd: '123456'   });   ToastAndroid.show('添加数据完成',
    // ToastAndroid.SHORT); });
    AsyncStorage.getItem('isLogin', (error, result) => {
      if (!error) {
        if (result == 'true') {
          this
            .props
            .navigator
            .push({component: MyNavigator});
          realm.close();
        }
      }
    });
  }

  /**
   * 登录判断操作
   */
  getUser() {
    let user = realm.objects('user');
    let u = user.filtered("name='" + this.state.userName + "' and pwd='" + this.state.userPwd + "'");
    if (u.length > 0) {
      this
        .props
        .navigator
        .push({component: MyNavigator});
      realm.close();
      //存储登录状态
      AsyncStorage.setItem('isLogin', 'true', function (error) {
        if (error) {
          ToastAndroid.show("存储失败", ToastAndroid.SHORT);
        } else {
          ToastAndroid.show("已登录", ToastAndroid.SHORT);
        }
      })

    } else {
      ToastAndroid.show("用户名或密码输入错误", ToastAndroid.SHORT);
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <TitleBarView navigator={this.props.navigator} text="退出"/>
        <View style={styles.imgHeader}>
          <Image
            source={require('../../../images/login_top.png')}
            resizeMode={Image.resizeMode.stretch}/>
        </View>
        <View style={styles.body}>
          <View style={{
            flexDirection: 'row-reverse'
          }}>
            <Text
              style={{
              color: '#7EC0EE',
              marginLeft: 15,
              marginTop: 8,
              marginRight: 15,
              fontSize: 17
            }}>网络状态:WIFI已连接</Text>
          </View>
          <View style={styles.inputView}>
            <View style={{
              flexDirection: 'row'
            }}>
              <Image
                source={require('../../../images/username.png')}
                resizeMode={Image.resizeMode.stretch}
                style={styles.inputImage}/>
              <TextInput
                placeholder='用户名'
                underlineColorAndroid='transparent'
                style={styles.textInput}
                onChangeText={(userName) => this.setState({userName})}/>
            </View>
            <View style={{
              flexDirection: 'row'
            }}>
              <Image
                source={require('../../../images/user_password.png')}
                resizeMode={Image.resizeMode.stretch}
                style={styles.inputImage}/>
              <TextInput
                placeholder='密码'
                secureTextEntry
                ={true}
                password={true}
                underlineColorAndroid='transparent'
                style={styles.textInput}
                onChangeText={(userPwd) => this.setState({userPwd})}/>
            </View>
          </View>
          <View
            style={{
            alignItems: 'center',
            marginBottom: 10,
            flexDirection: 'row-reverse',
            marginLeft: 15
          }}>
            <Text>记住密码</Text>
            <Switch
              value={this.state.isMemoryPwd}
              onValueChange={(value) => {
              this.setState({isMemoryPwd: value});
            }}/>
          </View>
          <View
            style={{
            marginLeft: 15,
            marginRight: 15
          }}>
            <Button
              onPress={() => {
              this.getUser();
            }}
              title="登录"
              color="#6495ED"/>
          </View>
        </View>
      </View>

    );
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值