跳转到正文
返回

React Native 异步存储

封装操作 RNstorage 的函数

<!-- storage.js -->

import { AsyncStorage } from 'react-native'

async function save(key, value) {
  try {
    // console.log("Set item: %s, %o", key, value)
    await AsyncStorage.setItem(key, value)
  } catch (error) {
    // console.log("Set item fail %o", error)
  }
}

async function query(key) {
  try {
    // console.log("Get item: %s", key)
    let value = await AsyncStorage.getItem(key)
    return value
  } catch (error) {
    // console.log("Get item fail %o", error)
  }
}

async function remove(key) {
  try {
    // console.log("Remove item: %s", key)
    await AsyncStorage.removeItem(key)
  } catch (error) {
    // console.log("Remove item fail %o", error)
  }
}

export { save, query, remove }

存、取、删的使用

import { save, query, remove } from'./storage'

<!-- 存 -->

save('localSave', JSON.stringify(response.user)) /**存储时要转为JSON字符串*/

<!-- 取 -->
async function name() {
   let localSave = await query('localSave')  /*存储的localSave */
}
  name()

/**使用时 取出的数据要处理下  JSON.parse(localSave)
*/

<!-- 删出storage的函数-->

async function rmFun() {
  remove('token')
  remove('users')
}