(十)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>

    );
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章