具有 redux-persist 的对象的 React-Native Persist 对象

React-Native Persist object of objects with redux-persist

我在 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 } ];

有个"cleaner solution"??

这是一个适用于您的案例的示例:

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); 应该 return 你可以用来创建商店的 rootReducer

我使用的最终解决方案是更改减速器:

  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 } };