0
点赞
收藏
分享

微信扫一扫

010.本地持久库

小磊z 2022-04-22 阅读 38
reactnative

https://github.com/sunnylqm/react-native-storage

  • 安装@react-native-community/async-storage
yarn add @react-native-community/async-storage
yarn add react-native-storage
  • 创建storage.ts操作库

在这里插入图片描述

import AsyncStorage from "@react-native-community/async-storage";
import Storage, { LoadParams } from "react-native-storage";

const storage = new Storage({
    size: 1000,//最大容量,默认值1000条数据循环存储
    //数据引擎,对于RN使用AsyncStorage,对于web使用window.localStorage
    // 如果不指定则数据只会保存在内存中,重启后即丢失
    storageBackend: AsyncStorage,
    defaultExpires: 1000 * 3600 * 24 * 7,//过期时间7天,null:不过期
    enableCache: true,//读写时在内存中缓存数据。默认启用。
    // 如果storage中没有相应数据,或数据已过期,
    // 则会调用相应的sync方法,无缝返回最新数据。
    sync: {

    }
});

const load = (params: LoadParams) => {
    return storage.load(params)
}

export { load }
export default storage
  • 使用Storage
//本地数据
import storage, { load } from '@/config/storage';

 获取数据
*asyncCategoryList({ _ }, { call, put }) {
     //从storage获取数据
     const myCategorys: CategoryType[] = yield call(load, { key: 'myCategorys' })
     const categorys: CategoryType[] = yield call(load, { key: 'categorys' })
     //发起action,将数据保存到state
        if (myCategorys) {
            yield put({
                type: 'setStates',
                payload: {
                     myCategorys: [...myCategorys],
                     categorys: [...categorys]
                 }
            })
         } else {
            yield put({
                type: 'setStates',
                payload: {
                    categorys: [...categorys]
                }
            })
         }
},


或者
//const myCategorys: CategoryType[]  =  yield storage.load({key:'myCategorys'})


//保存数据到storage
storage.save({
      key: 'myCategorys',
      data: payload.myCategorys,
});

//给store的sync赋值
//给categorys赋值
 storage.sync.categorys = async () => {
       const response = await getCategoryList();
       if (response && response instanceof Object) {
            const { data } = response
            return data
        }
}
//给myCategorys 赋值
storage.sync.myCategorys = async () => {
       return null
}

举报

相关推荐

0 条评论