当前位置: 首页 > 工具软件 > React Native > 使用案例 >

《ReactNative》之AsyncStorage的封装

姜凯风
2023-12-01

 

AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。它用来代替LocalStorage。

安装

npm install @react-native-community/async-storage

1.封装为DeviceStorage.js类

import AsyncStorage from '@react-native-community/async-storage';
export default class DeviceStorage{
  static save = async (key, value) => {
    try {
      const result = await AsyncStorage.setItem(key, value)
      console.log('save result', result)
    } catch (e) {
      console.log('error',e)
      // saving error
    }
  }
  static get = async (key) => {
    try {
      const value = await AsyncStorage.getItem(key);
      //console.log('--value-',value)
      return JSON.parse(value);
    } catch(e) {
      console.log('error',e)
      // error reading value
    }
  }
}

 

 

2.使用

2.1 导入DeviceStorage.js

import DeviceStorage from 'xxx/DeviceStorage';

2.2 保存

 

const list = [
    {title: 'test1'},
    {title: 'test2'}
}
DeviceStorage.save('xxxList',JSON.stringify(list))

2.3 获取

componentWillMount=async() => {
    const list = await DeviceStorage.get('xxxList')
 }

 

 

 

 

 

 

 

 

 

 类似资料: