react native开发之数据持久化(asyncstorage)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/douzhenwen/article/details/80499972
react native提供的asyncstorage是一个简单的,异步的,持久的键值对储存系统,它对与app来说是全局性的,只能储存字符串类型
getItem(key,(error,result)=>{}):通过key获取值。 
setItem(key, value,(error)=>{}):保存 
removeItem(key,(error)=>{}):删除 
clear((error)=>{}):清除所有数据,不建议使用。 
getAllKeys((error,arrays)=>{}):获取所有的key。 
multiGet(keys,(errors,arrays)=>{}):获取多个key的value值 
multiSet:保存多个数据,multiSet([[‘k1’, ‘val1’], [‘k2’, ‘val2’]], cb); 
multiRemove:移除多个数据,multiRemove([‘key1’,’key2’],(errors)=>{})
代码
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    AsyncStorage,
    Button,
    Alert,
    Text,
    TextInput,
} from 'react-native';

export default class AsyncStorageDemo extends Component {

    static navigationOptions = {
        title: 'AppState'
    }

    state = {
        key:'',
        value:'',
        data: '\n',
    }

    _getAll = () => {
        this.setState({data: '\n'});
        AsyncStorage.getAllKeys((err,keys) => {
            if (keys && keys.length>0) {
                keys.map((key, index) => {
                    AsyncStorage.getItem(key, (err, result) => {
                        var msg = this.state.data+key + ': ' + result + '\n';
                        this.setState({data: msg});
                    })
                });
            }
        })
    }
    _add = () => {
        AsyncStorage.setItem(this.state.key, this.state.value, (error) => {
            if (error == null) {
                Alert.alert('保存成功');
            } else {
                Alert.alert('error');
            }
        })
    }

    _remove = ()=>{
        AsyncStorage.removeItem(this.state.key,(error)=>{
            if (error == null) {
                Alert.alert('删除成功');
            } else {
                Alert.alert('error');
            }
        })
    }
    render() {
        return (
            <View style={{flex:1}}>
                <TextInput style={{height:50,borderColor:'gray',borderWidth:1}} placeholder='key' onChangeText={(txt)=>{this.setState({key:txt})}} value={this.state.key}/>
                <TextInput style={{height:50,borderColor:'gray',borderWidth:1}} placeholder='value' onChangeText={(txt)=>{this.setState({value:txt})}} value={this.state.value}/>
                <Button title='ADD' onPress={this._add}/>
                <Button title='REMOVE' onPress={this._remove}/>
                <Button title='GET' onPress={this._getAll}/>
                <Text>data:{this.state.data}</Text>
            </View>
        );
    }
}
需要在index.js中注册
展开阅读全文

没有更多推荐了,返回首页