无法使用简单的方法在 React Native 中持久化状态



当将AsyncStorage作为存储引擎传递时,我收到以下错误:

WARN  Possible Unhandled Promise Rejection (id: 0):
Error: [AsyncStorage] Passing null/undefined as value is not supported. If you want to remove value, Use .removeItem method instead.
Passed value: undefined
Passed key: [EasyPeasyStore][0]

这是我的店铺申报单:

import { action, createStore, persist } from "easy-peasy";
import AsyncStorage from "@react-native-async-storage/async-storage";
const store = createStore(
persist({
...my state goes here
}, {
storage: AsyncStorage
})
);

尝试添加允许属性

const store = createStore(
persist({
...my state goes here
}, {
allow: ['state attributes here ex. user'],
storage: AsyncStorage
})

);

在花了大量时间调试和搜索GitHub问题之后,这就是我找到的解决方案。在这里很有魅力。此外,您还需要允许持久化哪些状态变量。

import { action, createStore, persist } from "easy-peasy";
import AsyncStorage from "@react-native-async-storage/async-storage";
const store = createStore(
persist({
...my state goes here
}, {
storage: {
getItem: async function (key){
console.log("GET_ITEM: ", key);
const value = await AsyncStorage.getItem(key);
return JSON.parse(value);
},
setItem: function (key, value){
console.log("SET_ITEM: ", key, value);
AsyncStorage.setItem(key, JSON.stringify(value))
}
},
allow: ['Names of the state variables to be persisted goes here']
})
);

最新更新