我在redux中处于这种状态:
draft: {
temporary: { clientId: null, shoppingCart: [] },
},
在我的购物车中,我使用 react-addons-update 推送一些对象:
const newState = { ...state };
let cart = newState.draft.temporary.shoppingCart;
cart = update(cart, { $push: [{ id: 1, quantity: 3 }] });
newState.draft.temporary.shoppingCart = cart;
return newState;
,我在应用程序中的newState是:
draft: {
temporary: { clientId: null, shoppingCart: [
{id: 1, qnt: 3},
]},
},
我用以下方法配置 products 减速器:
products: persistReducer(products: {
key: 'products',
storage,
whitelist: ['draft'],
}, products),
但是一旦重新加载应用程序,我的商店就不会保留。
更新:
有效的示例解决方案:
newState.draft = { ...newState.draft, temporary: { ...newState.draft.temporary, shoppingCart: [ ...newState.draft.temporary.shoppingCart, { id: 1, qnt: 3 } ]}};
没有 react-addons-update 的解决方案不起作用:
newState.draft.temporary.shoppingCart = [ ...newState.draft.temporary.shoppingCart, { id: payload.id, quantity: 1 } ];
有一种“更清洁的解决方案”?
答案 0 :(得分:0)
以下是一个适合您情况的示例:
import { persistCombineReducers, persistReducer } from 'redux-persist';
const draftPersistConfig = {
key: 'draft',
storage: AsyncStorage
};
const reducers = {
products: persistReducer(draftPersistConfig, products),
// ...other reducers if you have any
}
const persistConfig = {
key: 'root',
storage: AsyncStorage,
debug: true,
whitelist: ['draft']
};
persistCombineReducers(persistConfig, reducers);
应该返回您可以用来创建商店的rootReducer
答案 1 :(得分:0)
我使用的最终解决方案是更换减速器:
const newDraft = { ...state.draft };
let cart = state.draft.temporary.shoppingCart;
const index = _.findIndex(cart, { id: payload.id });
if (index === -1) cart = update(cart, { $push: [{ id: payload.id, quantity: 1 }] });
else cart = update(cart, { [index]: { quantity: { $set: cart[index].quantity + 1 } } });
newDraft.temporary.shoppingCart = cart;
return { ...state, draft: { ...newDraft } };