AsyncStorage 简单封装

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

安装方式:

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");
}