React-Native 异步存储storage

封装操作 RNstorage 的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!-- 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 }

存、取、删的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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')
}