带有 redux 存储的 AsyncStorage
AsyncStorage with redux store
我正在使用 Redux 来管理购物车状态,但是在重新启动应用程序时,购物车状态变为空。为了解决,我想到了使用 AsyncStorage 来存储数据并在 componentDidMount 中获取它,但它显示 null 而不是购物车数据。
还原操作代码
case 'ADD_TO_CART':
{
const updatedCart = [...state.cart];
const item = updatedCart.find(x=>x.key===action.payload.key);
if(item)
{
item.count++;
}
else{
updatedCart.push(action.payload);
}
AsyncStorage.setItem('cart',{...state,cart: updatedCart,total: state.total + 1})
return {
...state,
cart: updatedCart,
total: state.total + 1,
}
}
正在获取数据
async componentDidMount() {
const item = await AsyncStorage.getItem('cart'))
console.log(item)
}
我还有一项删除购物车商品的操作,其中使用相同的 setItem 方法设置购物车状态。
当你将一个对象设置为异步存储时,它应该是一个字符串而不是一个对象,所以使用 JSON.strigify 并像下面这样设置项目
AsyncStorage.setItem('cart',JSON.stringify({...state,cart: updatedCart,total: state.total + 1}));
当你得到物品时,使用 JSON.parse() 来解析它们,如下所示
const item = await AsyncStorage.getItem('cart'))
console.log(JSON.parse(item))
由于您的要求是保持 redux 状态,请考虑使用
https://github.com/rt2zz/redux-persist
这将在您关闭应用程序时保持状态。
我正在使用 Redux 来管理购物车状态,但是在重新启动应用程序时,购物车状态变为空。为了解决,我想到了使用 AsyncStorage 来存储数据并在 componentDidMount 中获取它,但它显示 null 而不是购物车数据。
还原操作代码
case 'ADD_TO_CART':
{
const updatedCart = [...state.cart];
const item = updatedCart.find(x=>x.key===action.payload.key);
if(item)
{
item.count++;
}
else{
updatedCart.push(action.payload);
}
AsyncStorage.setItem('cart',{...state,cart: updatedCart,total: state.total + 1})
return {
...state,
cart: updatedCart,
total: state.total + 1,
}
}
正在获取数据
async componentDidMount() {
const item = await AsyncStorage.getItem('cart'))
console.log(item)
}
我还有一项删除购物车商品的操作,其中使用相同的 setItem 方法设置购物车状态。
当你将一个对象设置为异步存储时,它应该是一个字符串而不是一个对象,所以使用 JSON.strigify 并像下面这样设置项目
AsyncStorage.setItem('cart',JSON.stringify({...state,cart: updatedCart,total: state.total + 1}));
当你得到物品时,使用 JSON.parse() 来解析它们,如下所示
const item = await AsyncStorage.getItem('cart'))
console.log(JSON.parse(item))
由于您的要求是保持 redux 状态,请考虑使用 https://github.com/rt2zz/redux-persist 这将在您关闭应用程序时保持状态。