RN-AsyncStorage

基本概念

1 AsyncStorage

* AsyncStorage 是一個簡單的、異步的、持久化的 Key-Value 存儲系統(tǒng),它對于 App 來說是全局性的。它用來代替 LocalStorage。
* 由于它的操作是全局的,官方建議我們最好針對 AsyncStorage 進行一下抽象的封裝再使用,而且不是直接拿 AsyncStorage 進行使用。 (react-native-storage)
* AsyncStorage 存儲的位置根據(jù)系統(tǒng)的不同而有所差異。iOS 中的存儲類似于 NSUserDefault,通過 plist 文件存放在設(shè)備中。Android 中會存儲在 RocksDB 或者 SQLite 中,取決于你使用哪個。

2 相關(guān)方法

根據(jù)鍵來獲取值, 獲取的值放在回調(diào)函數(shù)中

static getItem(key: string, callback:(error, result))

根據(jù)鍵來設(shè)置值。

static setItem(key: string, value: string, callback:(error))

根據(jù)鍵來移除項。

static removeItem(key: string, callback:(error))

合并現(xiàn)有值和輸入值。

static mergeItem(key: string, value: string, callback:(error))

清除所有的項目

static clear(callback:(error))

獲取所有的鍵

static getAllKeys(callback:(error, keys))

清除所有進行中的查詢操作。

static flushGetRequests()

獲取多項,其中 keys 是字符串數(shù)組,比如:['k1', 'k2']

static multiGet(keys, callback:(errors, result))

設(shè)置多項,其中 keyValuePairs 是字符串的二維數(shù)組,比如:[['k1', 'val1'], ['k2', 'val2']]

static multiSet(keyValuePairs, callback:(errors))

刪除多項,其中 keys 是字符串數(shù)組,比如:['k1', 'k2']

static multiRemove(keys, callback:(errors))

多個鍵值合并,其中 keyValuePairs 是字符串的二維數(shù)組,比如:[['k1', 'val1'], ['k2', 'val2']]

static multiMerge(keyValuePairs, callback:(errors))

3 使用

/**
 * Created by licc on 2017/7/13.
 */

import React, { Component }from  'react';
import  {
    AsyncStorage,
    Button,
    View,
    Text,
    TextInput,
    TouchableHighlight,
    StyleSheet
} from  'react-native';

import NavigationBar from './NavigationBar'

export default class AsyncStorageExample extends Component {

    constructor(props){
        super(props);

        this.state = {
            username:'',
            password:''
        }
    }

    componentDidMount(){

        var keys = ['username', 'password'];
        AsyncStorage.multiGet(keys, (errs, result)=>{

            var _that = this;

            if (errs) return;

            _that.setState({
                username:(result[0][1]!== null)? result[0][1]:'',
                password:(result[1][1]!== null)? result[1][1]:''
            });
        });
    }

    render(){
        return (
            <View>
                <NavigationBar
                    title={'登錄'}
                    statusBar={{backgroundColor:'blue'}}
                />
                <View style={styles.row}>

                    <View style={styles.head}>
                        <Text style={styles.label}>用戶名</Text>
                    </View>

                    <View style={styles.flex}>
                        <TextInput
                            style={styles.input}
                            value = {this.state.username}
                            onChangeText={(username)=>this.setState({username})}
                        />
                    </View>

                </View>


                <View style={styles.row}>

                    <View style={styles.head}>
                        <Text style={styles.label}>密碼</Text>
                    </View>

                    <View style={styles.flex}>
                        <TextInput
                            style={styles.input}
                            value={this.state.password}
                            onChangeText={(password)=>this.setState({password})}
                        />
                    </View>

                </View>


                <View style={styles.row}>
                        <Text style={styles.btn} onPress={this.doLogin.bind(this)}>登錄</Text>
                        <Text style={styles.btn} onPress={this.clear.bind(this)}>清除</Text>
                </View>

            </View>
        );
    }


    doLogin(){

       let info = [['username', this.state.username], ['password', this.state.password]]

        AsyncStorage.multiSet(info, (errs)=>{
            if (errs) {
                alert('登錄失敗');
                return;
            }

            alert('登錄成功');
        });
    }

    clear(){
        AsyncStorage.clear((errs)=>{
           if (!errs){
               this.setState({
                   username:'',
                   password:''
               });

               alert('存儲的數(shù)據(jù)已清除完畢!');
           }
        });
    }




}

const styles = StyleSheet.create({

    flex:{
        flex:1,
    },

    topStatus:{
        marginTop:25,
    },

    row:{
        flexDirection:'row',
        height:55,
        paddingTop:10
    },

    head:{
        width:80,
        marginLeft:5,
        backgroundColor:'#23BEFF',
        height:45,
        justifyContent:'center',
        alignItems: 'center'
    },

    label:{
        color:'#fff',
        fontSize:15,
        fontWeight:'bold'
    },

    input:{
        height:45,
        borderWidth:1,
        marginRight: 5,
        paddingLeft: 10,
        borderColor: '#ccc'
    },

    btn:{
        flex:1,
        backgroundColor:'#FF7200',
        height:45,
        textAlign:'center',
        color:'#fff',
        marginLeft:5,
        marginRight:5,
        lineHeight:45,
        fontSize:15,
    },

});

*注 第三方封裝
react-native-storage

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 和Sets相比,SortedSets增加了一個權(quán)重參數(shù)score,使得集合中的元素能夠按score進行有序排列, ...
    架構(gòu)飛毛腿閱讀 4,004評論 0 0
  • 1.概述 1.AsyncStorage 是一個簡單的、異步的、持久化的 Key-Value 存儲系統(tǒng),它對于 Ap...
    AISpider閱讀 2,666評論 0 0
  • 余知霖臉色慘白,“不要……余溯,余溯他要抓我去給大佬?!悠?,我怕……”余知霖的聲音帶著顫抖,林子祁鎮(zhèn)定的握住她一...
    阿九小叔閱讀 269評論 0 1
  • 無早起,四重奏 EnglishPod C0006打卡! 《四重奏》太戳人心了,特別是我這樣只是單相思的人。 “我喜...
    披著馬甲寫日記閱讀 312評論 0 0
  • 暗戀,是世界上最卑微的感情,不敢為人知,不敢去觸碰,即使是最不經(jīng)意的擦肩而過,也會心跳加速。懊惱與歡喜許久,惱的是...
    偶遇西西閱讀 280評論 0 0

友情鏈接更多精彩內(nèi)容