RN AsyncStorage的使用

本文介绍React Native中使用AsyncStorage进行数据存储的方法,包括保存、查询和删除数据的操作,并提供了一个完整的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做web的时候保存数据常用的是cookie或者localstorage,那在移动端用什么呢?RN提供了AsyncStorage!

代码走起:

AsyncStorage在RN里自带的,不用npm install,直接引用即可~

import { View, Text, StyleSheet, AsyncStorage } from 'react-native';

操作就是增删改查,先是增(存)改同样的道理,同样的KEY,再存一次就是覆盖,自然就是改了。

    //保存数据
    asSave = () => {
        AsyncStorage.setItem(AS_KEY, this.state.valueCustom, (error) => {
            if (!error) {
                this.toast.show('保存数据成功', DURATION.LENGTH_SHORT);
            } else {
                this.toast.show('保存数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //查询保存的数据
    asQuery = () => {
        AsyncStorage.getItem(AS_KEY, (error, result) => {
            if (!error) {
                if (result !== '' && result !== null) {
                    // this.toast.show('查询到的内容是:' + result, DURATION.LENGTH_SHORT);
                    this.setState({
                        valueCustom: result,
                    });
                } else {
                    this.toast.show('未找到指定保存的内容!', DURATION.LENGTH_SHORT);
                }
            } else {
                this.toast.show('查询数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //删除已经保存的数据
    asDelete = () => {
        AsyncStorage.removeItem(AS_KEY, (error) => {
            if (!error) {
                this.toast.show('删除数据成功', DURATION.LENGTH_SHORT);
                this.setState({
                    valueCustom: "",
                });
            } else {
                this.toast.show('删除数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

完成的demo如下:
 

import React, { Component } from 'react';
import { View, Text, StyleSheet, AsyncStorage } from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast';
import {Container, Header, Title, Content, Button} from 'native-base';
import { Overlay, Label, Select, Button as TButton} from 'teaset';

//AsyncStorage是以键值对的形式保存数据 ,诸如安卓中SharedPreferences一样
const AS_KEY = "hm_deviceCode"

export default class SetDevice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            valueCustom: "",  
        };
        this.customItems = [
            {
              text: 'test01',
              value: "1111",
            },
            {
              text: 'test02',
              value: "2222",
            }
        ];
    }

    componentDidMount() {
        this.asQuery();
    }

    //查询保存的数据
    asQuery = () => {
        AsyncStorage.getItem(AS_KEY, (error, result) => {
            if (!error) {
                if (result !== '' && result !== null) {
                    // this.toast.show('查询到的内容是:' + result, DURATION.LENGTH_SHORT);
                    this.setState({
                        valueCustom: result,
                    });
                } else {
                    this.toast.show('未找到指定保存的内容!', DURATION.LENGTH_SHORT);
                }
            } else {
                this.toast.show('查询数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //保存数据
    asSave = () => {
        AsyncStorage.setItem(AS_KEY, this.state.valueCustom, (error) => {
            if (!error) {
                this.toast.show('保存数据成功', DURATION.LENGTH_SHORT);
            } else {
                this.toast.show('保存数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //删除已经保存的数据
    asDelete = () => {
        AsyncStorage.removeItem(AS_KEY, (error) => {
            if (!error) {
                this.toast.show('删除数据成功', DURATION.LENGTH_SHORT);
                this.setState({
                    valueCustom: "",
                });
            } else {
                this.toast.show('删除数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    onSelected = (item, index) => {
        this.setState({
            valueCustom: item.value
        },()=>{
            this.asSave();
        });
    }

    render() {
        return (
            <Container>
                <Header>
                    <Title>
                        <Text style={{
                            lineHeight: 53,
                        }}>设备配置</Text>
                    </Title>
                </Header>

                <Content style={styles.content}>
                    <View style={{
                        display: 'flex',
                        flexDirection: 'row',
                        alignItems: "center",
                        justifyContent: "space-around"
                    }}>
                        <Label size='md' text='请选择当前设备:' />
                        <Select
                            style={{width: 200, backgroundColor: '#fcf8e3', borderColor: '#8a6d3b'}}
                            value={this.state.valueCustom}
                            valueStyle={{flex: 1, color: '#8a6d3b', textAlign: 'center'}}
                            items={this.customItems}
                            getItemValue={(item, index) => item.value}
                            getItemText={(item, index) => item.text}
                            iconTintColor='#8a6d3b'
                            placeholder='Select item'
                            pickerTitle='已有设备'
                            onSelected={(item, index) => this.onSelected(item, index)}
                        />
                        <TButton title='清除' onPress={() => this.asDelete()} />
                    </View>
                </Content>
                <Toast ref={v => this.toast = v}/>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    content: {
        margin: 5
    },
});

 

<think>嗯,用户问的是React Native中使用localForage的情况,我需要先确认localForage在React Native中的适用性。首先,localForage是一个前端库,主要用于改善本地存储体验,支持IndexedDB、WebSQL和localStorage。不过React Native的环境和浏览器不同,可能需要额外的配置。 然后,我应该考虑React Native的存储机制。通常,AsyncStorage是React Native自带的,但localForage可能提供了更友好的API和更好的异步处理。需要查证localForage是否支持React Native,或者是否需要使用localForage的React Native驱动,比如localforage-react-native。 接下来,可能需要安装步骤。用户需要安装localforage和可能的适配器,比如使用npm或yarn安装。然后,配置localForage使用React Native的AsyncStorage作为驱动。这部分需要给出具体的代码示例,比如如何引入和配置。 另外,要提到localForage的优点,比如支持Promise,自动选择后端驱动,数据序列化等。同时,也要注意潜在的问题,比如在React Native中某些驱动可能不可用,需要确保正确配置AsyncStorage驱动。 还有,使用场景。比如在离线应用、缓存数据或存储用户偏好时的应用。可能还需要比较一下localForage和直接使用AsyncStorage的区别,强调localForage的便利性和统一性。 最后,给出一个简单的使用示例,比如存储和读取数据,错误处理等。确保代码语法正确,使用$$...$$格式展示独立代码块,行内变量用$...$。同时提醒用户注意异步操作和可能的兼容性问题。</think>在React Native中使用localforage的步骤如下,我将以清晰的逻辑逐步说明: $$ \text{localforage} = \text{前端存储库} + \text{React Native适配层} $$ 一、核心概念 1. **定位**:localforage是改进版异步存储库,默认支持IndexedDB/WebSQL/localStorage 2. **React Native适配**:通过`localforage-react-native`驱动,底层使用AsyncStorage 3. **特性**: - 支持Promise API - 自动处理数据类型序列化(可存储对象/二进制数据) - 统一接口兼容多平台 二、安装配置 1. 安装基础库: ```bash yarn add localforage ``` 2. 添加React Native驱动: ```bash yarn add localforage-react-native ``` 3. 初始化配置(App入口文件): ```javascript import localforage from 'localforage'; import { AsyncStorage } from 'react-native'; localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE, localforage.REACTNATIVESTORAGE ], name: 'MyAppStorage', storeName: 'custom_store', asyncStorage: AsyncStorage // 关键配置 }); ``` 三、核心API(均返回Promise) 1. 存储数据: ```javascript await localforage.setItem('key', { complex: { data: true } }); ``` 2. 读取数据: ```javascript const value = await localforage.getItem('key'); ``` 3. 删除数据: ```javascript await localforage.removeItem('key'); ``` 4. 清空存储: ```javascript await localforage.clear(); ``` 四、性能优化建议 1. 批量操作使用`iterate`: $$ \text{遍历效率} \propto \frac{1}{\text{独立操作次数}} $$ ```javascript localforage.iterate((value, key) => { console.log($key$, $value$); }); ``` 2. 配置存储引擎优先级: ```javascript localforage.setDriver([ localforage.REACTNATIVESTORAGE, localforage.INDEXEDDB ]); ``` 五、注意事项 1. 数据类型限制: - 支持:String/Number/Object/Array/Blob - 限制:存储大小受AsyncStorage限制(约6MB) 2. 错误处理: ```javascript try { await localforage.setItem('key', data); } catch (error) { console.error($存储失败: ${error.message}$); } ``` 六、与AsyncStorage对比 | 特性 | localforage | AsyncStorage | |--------------------|----------------------|------------------| | 接口类型 | Promise | Callback/Promise | | 数据序列化 | 自动处理 | 需手动JSON处理 | | 存储类型支持 | 丰富 | 仅字符串 | | 多后端支持 | 是 | 否 | 七、典型应用场景 1. 离线数据缓存 2. 用户偏好设置持久化 3. 大文件分块存储(需配合Blob处理) 4. 跨平台存储方案统一 建议在实际开发中结合React Native的`NetInfo`模块实现完整的离线功能方案: $$ \text{离线体验} = \text{localforage存储} + \text{网络状态监听} + \text{数据同步策略} $$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值