React Native学习之AsyncStorage API

AsyncStorage是一个简单的、具有异步特性的键值对的存储系统,并且是全局的!替代LocalStorage。相当于 Android 中的SharedPreference和 iOS 中的NSUserDefalut

AsyncStorage里面都有一个回调函数,而回调的第一个参数都是错误对象,如果发生错误,该对象就会展示错误信息,否则为null;每个方法都会返回一个Promise对象。

获取AsyncStorage中存储的数据,一定是在DidMount生命周期里,不能在WillMount里。

  • static getItem(key: string, callback: (error, result)):根据键来获取值,获取的结果会在回调函数中
  • static setItem(key: string, value: string, callback: (error)): 设置键值对
  • static removeItem(key: string, callback: (error)):将根据键移出一项
  • static mergeItem(key: string, value: string, callback: (error)):合并现有的值和输入值
  • `static clear(callback: (error)):清除所有的项目
  • static getAllKeys(callback: (error)):获取所有的键
  • static multiGet(keys, callback: (errors, result)):获取多项,其中keys是字符串数组。
  • static multiSet(keyValuePairs, callback: (error)):设置多项,其中keyValuePairs是字符串的二维数组
  • static multiRemove(keys, callback: (error)):删除多项,其中keys是字符串数组
  • static multiMerge(keyValuePairs, callback: (error)):多个键值合并,其中keyValuePairs是字符串中的二维数组

案例:购物车(数据共享),包含列表页和结算页

  • 数据模型构建
  • 列表项Item组件(es6中默认属性与属性类型的定义)
  • 列表组件List
  • 购物车组件
  • 串联组件

推荐由React Native中文网封装维护的react-native-storage模块,提供了较多便利功能。

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    Navigator,
    ScrollView,
    Image,
    AsyncStorage,
    TouchableOpacity,
    View,
} from 'react-native';

import Dimensions from 'Dimensions';

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

const Model = [
    {
        id: '1',
        title: '红心猕猴桃',
        desc: '12个装70-90g/个',
        price: 49,
        url: 'http://note.youdao.com/yws/api/personal/file/62EAF0C6AC8142EA89B11A71BB6C8AEC?method=download&inline=true&shareKey=e6b1c5b1307f752c9e4925056a4facd9',
    },
    {
        id: '2',
        title: '红富士苹果',
        desc: '5kg果径80-85mm',
        price: 109,
        url: 'http://note.youdao.com/yws/api/personal/file/E38B11859CB2496190BF5A559D9E68B5?method=download&inline=true&shareKey=1dabf3633a1051e9f5d2d7470fd91c0b',
    },
    {
        id: '3',
        title: '哈密瓜',
        desc: '2个装1.4kg以上/个',
        price: 42,
        url: 'http://note.youdao.com/yws/api/personal/file/F443648C199346FDA7E48AE88D0D00A2?method=download&inline=true&shareKey=89fdcc577f98ecdddfcf03f575767381',
    },
    {
        id: '4',
        title: '青芒',
        desc: '1kg500g以上/个',
        price: 28,
        url: 'http://note.youdao.com/yws/api/personal/file/8F7B83A47CA94435A2132DC0341AECC3?method=download&inline=true&shareKey=d679e8800b5678f9c673538b93dc0fbc',
    },
    {
        id: '5',
        title: '黑珍珠葡萄',
        desc: '1kg装',
        price: 32,
        url: 'http://note.youdao.com/yws/api/personal/file/AF297F8C75714DE481E87C6F09D97649?method=download&inline=true&shareKey=8f89c3673e8851efb20abccce2214fbf',
    },
    {
        id: '6',
        title: '红心火龙果',
        desc: '2.5kg装250-350g/个',
        price: 59.9,
        url: 'http://note.youdao.com/yws/api/personal/file/B67D0D453865459594C0FDC6CDE95A79?method=download&inline=true&shareKey=3bc5b3b1ee9f13e3a7ebdd251d117796',
    },
];

class RNAPP extends Component {
    render() {
        let defaultName = 'Home';
        let defaultComponent = Home;
        return (
            <Navigator
                initialRoute = {{ name: defaultName, component: defaultComponent }}
                //配置场景
                configureScene = {
                    (route) => {
                        //这个是页面之间跳转时候的动画,具体有哪些?可以看这个目录下,有源代码的: node_modules/react-native/Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js
                        return Navigator.SceneConfigs.VerticalDownSwipeJump;
                    }
                }
                renderScene = {
                    (route, navigator) => {
                        let Component = route.component;
                        return <Component {...route.params} navigator={navigator} />
                    }
                }
            />
        );
    }
}

class Home extends Component {
    render() {
        return (
            <List navigator={this.props.navigator} />
        );
    }
}

class Item extends Component {
    static defaultProps = {
        url: '',
        title: '默认标题',
    };

    static propTypes = {
        url: React.PropTypes.string.isRequired,
        title: React.PropTypes.string.isRequired,
    };

    render() {
        return (
            <View style={styles.item}>
                <TouchableOpacity onPress={this.props.press}>
                    <Image
                        resizeMode='stretch'
                        style={styles.img}
                        source={{ uri: this.props.url }}
                        >
                        <Text numberOfLines={1} style={styles.item_text}>{this.props.title}</Text>
                    </Image>
                </TouchableOpacity>
            </View>
        );
    }
}

class List extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
    }

    render() {
        let list = [];
        for (let i in Model) {
            if (i % 2 === 0) {
                //两个等号:不判断类型
                //三个等号:判断类型
                let row = (
                    <View style={styles.row} key={i}>
                        <Item
                            title={Model[i].title}
                            url={Model[i].url}
                            press={this.press.bind(this, Model[i]) }
                            >
                        </Item>
                        <Item
                            title={Model[parseInt(i) + 1].title}
                            url={Model[parseInt(i) + 1].url}
                            press={this.press.bind(this, Model[parseInt(i) + 1]) }
                            >
                        </Item>
                    </View>
                );
                list.push(row);
            }
        }

        let count = this.state.count;
        let str = null;
        if (count) {
            str = ', 共' + count + '件商品';
        }
        console.log('count=' + count);

        return (
            <ScrollView style={{ marginTop: 10 }}>
                {list}
                <Text onPress={this.goGouWu.bind(this) } style={styles.btn}>去结算{str}</Text>
            </ScrollView>
        );
    }

    goGouWu() {
        //alert('点击了去购物车');
        const { navigator } = this.props;
        //为什么这里可以取得 props.navigator?请看上文:
        //<Component {...route.params} navigator={navigator} />
        //这里传递了navigator作为props
        const _that = this;
        if (navigator) {
            navigator.push({
                name: 'GouWu',
                component: GouWu,
                params:{
                    getCount: function(count) {
                        _that.setState({
                            count: count,
                        });
                        console.log('参数传回');
                    },
                },
            })
        }
    }

    press(data) {
        this.setState({
            count: this.state.count + 1,
        });
        //AsyncStorage异步存储
        AsyncStorage.setItem('SP-' + this.genId() + '-SP', JSON.stringify(data), function (err) {
            if (err) {
                //TODO:存储出错
                alert(err);
            } else {
                //alert('保存成功');
            }
        });
    }

    //生成随机ID:GUID 全局唯一标识符(GUID,Globally Unique Identifier)是一种由算法生成的二进制长度为128位的数字标识符
    //GUID生成的代码来自于Stoyan Stefanov
    genId() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        }).toUpperCase();
    }

    componentDidMount() {
        let _that = this;
        AsyncStorage.getAllKeys(
            function (err, keys) {
                if (err) {
                    //TODO:存储取数据出错
                    //给用户提示错误信息
                    console.log(err);
                } else {
                    console.log('读取成功的个数:'+keys.toString());
                }
                _that.setState({
                    count: keys.length,
                });
            }
        );
    }
}

class GouWu extends Component {
    constructor(props) {
        super(props);
        this.state = {
            price: 0,
            data: [],
        };
    }

    render() {
        //第二次render的时候 data不为空
        let data = this.state.data;
        let price = this.state.price;
        let list = [];
        for (let i in data) {
            price += parseFloat(data[i].price);
            list.push(
                <View style={[styles.row, styles.list_item]} key={i}>
                    <Text style={styles.list_item_desc}>
                        {data[i].title}
                        {data[i].desc}
                    </Text>
                    <Text style={styles.list_item_price}>人民币: {data[i].price}</Text>
                </View>
            );
        }

        let str = null;
        if (price) {
            str = ', 共' + price.toFixed(2) + '元';
        }

        return (
            <ScrollView style={{ marginTop: 10 }}>
                {list}
                <Text style={styles.btn} onPress={this.paySuccess.bind(this)} >支付{str}</Text>
                <Text style={styles.clear} onPress={this.clearStorage.bind(this) }>清空购物车</Text>
            </ScrollView>
        );
    }

    componentDidMount() {
        let _that = this;
        AsyncStorage.getAllKeys(
            function (err, keys) {
                if (err) {
                    //TODO 存储数据出错
                    return;
                }
                //keys是字符串数组
                AsyncStorage.multiGet(keys, function (err, result) {
                    //得到的结构是二维数组
                    //result[i][0]表示我们存储的键,result[i][1]表示我们存储的值
                    let arr = [];
                    for (let i in result) {
                        arr.push(JSON.parse(result[i][1]));
                    }

                    _that.setState({
                        data: arr,
                    });
                });
            }
        );
    }

    paySuccess() {
        var _that = this;
        AsyncStorage.clear(function(err){
            if (!err) {
                _that.setState({
                    data: [],
                    price: 0,
                });

                const { navigator } = _that.props;
                if (_that.props.getCount) {
                    _that.props.getCount(0);
                }

                alert("支付成功!")

                if (navigator) {
                    navigator.pop();
                }
                //_that.props.navigator.pop();
            }
        });
    }

    clearStorage() {
        let _that = this;
        AsyncStorage.clear(function (err) {
            if (!err) {
                _that.setState({
                    data: [],
                    price: 0,
                });
                alert('购物车已经清空');
            }
        });
    }
}

const styles = StyleSheet.create({
    list_item: {
        marginLeft: 5,
        marginRight: 5,
        padding: 5,
        borderWidth: 1,
        height: 32,
        borderRadius: 3,
        borderColor: '#ddd',
    },
    list_item_desc: {
        flex: 2,
        fontSize: 15,
    },
    list_item_price: {
        flex: 1,
        fontSize: 15,
        textAlign: 'right',
    },
    clear: {
        marginTop: 10,
        backgroundColor: '#FF7200',
        color: '#fff',
        borderWidth: 1,
        borderColor: '#ddd',
        marginLeft: 10,
        marginRight: 10,
        lineHeight: 24,
        height: 33,
        fontSize: 18,
        textAlign: 'center',
        textAlignVertical: 'center',
    },
    btn: {
        flex: 1,
        backgroundColor: '#FF7200',
        height: 33,
        textAlign: 'center',
        textAlignVertical: 'center',
        color: '#fff',
        marginLeft: 10,
        marginRight: 10,
        lineHeight: 24,
        marginTop: 40,
        fontSize: 18,
    },
    row: {
        flexDirection: 'row',
        marginBottom: 10,
    },
    img: {
        flex: 1,
        backgroundColor: 'transparent',
    },
    item_text: {
        backgroundColor: '#000',
        opacity: 0.7,
        color: '#fff',
        height: 25,
        lineHeight: 18,
        textAlign: 'center',
        marginTop: 94,
    },
    item: {
        flex: 1,
        marginLeft: 5,
        borderWidth: 1,
        borderColor: '#ddd',
        marginRight: 5,
        height: 120,
    },
    list: {
        justifyContent: 'flex-start',
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    container: {

        flex: 1,
    },
    listView: {
        paddingTop: 20,
        backgroundColor: '#F5FCFF',
    },
    thumbnail: {
        width: 80,
        height: 80,
        borderRadius: 16,
    },
    //使rightContainer在父容器中占据Image之外剩下的全部空间
    container1: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    title: {
        fontSize: 14,
        marginBottom: 8,
    },
    year: {
        fontSize: 14,
    },
});

AppRegistry.registerComponent('RNAPP', () => RNAPP);

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/react-native-learning-for-asyncstorage-api/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
React Native学习之AsyncStorage API
AsyncStorage是一个简单的、具有异步特性的键值对的存储系统,并且是全局的!替代LocalStorage。相当于 Android 中的SharedPreference和 iOS 中的NSUserDefalu……
<<上一篇
下一篇>>
文章目录
关闭
目 录