海之飞燕

Menu
  • IOS
  • Swift
  • 前端开发
  • Flutter
  • ReactNative
  • Other
Menu

AsyncStorage 简单封装

Posted on 2020年2月23日2020年12月14日 by Herriat

AsyncStorage是一个简单的、异步的、持久化的 Key-Value 存储系统,它对于 App 来说是全局性的。可用来代替 LocalStorage。
ReactNative官网推荐我们在 AsyncStorage 的基础上做一层抽象封装,而不是直接使用AsyncStorage。

安装方式:
yarn add @react-native-community/async-storage

async-storage官网https://react-native-community.github.io/async-storage/docs/usage

可以用来存储string和object数据。

//导入async-storage库
import AsyncStorage from '@react-native-community/async-storage';

export default class DeviceStorage{
    static saveData = async (key, value) => {
      try {
        const result = await AsyncStorage.setItem(key, value)
        console.log('save result', result)
      } catch (e) {
        console.log('error',e)
      }
    }
    static getData = async (key) => {
      try {
        return await AsyncStorage.getItem(key);
      } catch(e) {
        console.log('error',e)
      }
    }

    static removeData = async (key) => {
      try {
        await AsyncStorage.removeItem(key)
      } catch (e) {
        console.log(e);
      }
  }
}

//使用方式
import DataStorage from '../utils/DataStorage';

//存储token
saveData("token",responseJson.data.token);

componentDidMount = async()=>{
    //获取token数据,判断是否登录
        const token = await DataStorage.getData('token')
        console.log('token',token);
        if(token){
            this.setState({
                isLogin:true
            })
        }else{
            this.setState({
                isLogin:false
            })
        }
   }
//调用退出登录,移除token
logout=()=>{
    DataStorage.removeData("token");
}

发表评论 取消回复

邮箱地址不会被公开。 必填项已用*标注

近期文章

  • WKWebView加载H5页面,退出时视频继续播放
  • Swift基础知识总结
  • ReactNative-Linking的基本使用
  • ReactNative进度条ProgressViewIOS
  • ReactNative中react-native-webview与js交互
  • ReactNative-SectionList

近期评论

  • Herriat发表在《curl、wget命令下载文件》
  • smm provider panel发表在《curl、wget命令下载文件》
  • www.scoop.it发表在《curl、wget命令下载文件》
  • 金玉游龙发表在《iOS9 Universal Links》
  • 十一岁的加重发表在《iOS-判断字符串是否是空字符串的方法》

文章归档

功能

  • 登录
  • 项目feed
  • 评论feed
  • WordPress.org

友情链接

金玉游龙 为吾优
©2021 海之飞燕 | WordPress Theme by Superbthemes.com