我试图在 redux reducer 中调用我的应用程序的当前状态。在第一种情况下,我使用此代码启动我的操作-</p>
store.dispatch(addNotificationID(item, 'start', notificationID));
console.log(item.id, 'start', notificationID);
console.log(store.getState().StorageReducer.IDs); //shows accurate state
这成功地触发了我的 redux reducer 的第一个案例,然后控制台日志console.log(store.getState().StorageReducer.IDs)
显示状态中新添加的 ID。然后,我有第二种情况,我最终将使用它从状态中删除 ID 对象。如果我重新加载应用程序,然后此操作触发类型CANCEL_NOTIFICATION
,它将记录正确的存储。但是,如果我在添加 ID 的同一会话中触发该操作,则不会登录到商店。
这是我的减速器:
const initialState = {
IDs: []
};
const storage = (state = initialState, action) => {
switch (action.type) {
case ADD_NOTIFICATION_ID:
return {
...state,
IDs:
[
...state.IDs,
{
itemID: action.item.id,
reminderType: action.reminderType,
notificationID: action.notificationID
}
]
};
case CANCEL_NOTIFICATION:
console.log(state.IDs);
return { ...state };
例如,假设应用程序启动时的 ID 是这样的:
Array [
Object {
"itemID": "_UE9dINF",
"notificationID": "F7AFB9F9-45C3-4A90-AD70-1A2334CE282A",
"reminderType": "start",
},
]
然后我的 addNotifications 动作触发。在那个会话中,当console.log(store.getState().StorageReducer.IDs)
被调用时,它看起来像这样:
Array [
Object {
"itemID": "_UE9dINF",
"notificationID": "F7AFB9F9-45C3-4A90-AD70-1A2334CE282A",
"reminderType": "start",
},
Object { //this is the new object that was just added to state
"itemID": "z4ACCSZR",
"notificationID": "3850E623-CFA7-483C-BF22-DB07C746CE37",
"reminderType": "start",
},
]
如果我重新加载会话然后触发 cancelNotification 操作,reducer 案例也会记录该输出。但是,如果我在同一个会话中运行该操作,我触发了 addNotifications 操作,而不是像上面那样,它只会看起来像这样:
Array [
Object {
"itemID": "_UE9dINF",
"notificationID": "F7AFB9F9-45C3-4A90-AD70-1A2334CE282A",
"reminderType": "start",
},
]
然后,如果我重新加载会话,它将具有应有的两个对象。我真的不明白为什么或如何做到这一点。我正在使用 redux-persist 并认为该错误可能来自某个地方。
我的 redux 商店:
const todoPersistConfig = {
key: 'TodoReducer',
storage: AsyncStorage,
whitelist: ['todos'],
stateReconciler: autoMergeLevel2
};
const storageConfig = {
key: 'StorageReducer',
storage: AsyncStorage,
whitelist: ['IDs'],
stateReconciler: autoMergeLevel2
};
const remindersPersistConfig = {
key: 'remindersreducer',
storage: AsyncStorage,
whitelist: ['notificationIDs'],
stateReconciler: autoMergeLevel2
};
const reducers = combineReducers({
ModalReducer,
RemindersReducer: persistReducer(remindersPersistConfig, RemindersReducer),
StorageReducer: persistReducer(storageConfig, StorageReducer),
TodoReducer: persistReducer(todoPersistConfig, TodoReducer),
AuthReducer
});
export default function storeConfiguration() {
const store = createStore(
reducers,
{},
composeEnhancers(
applyMiddleware(ReduxThunk)
)
);
const persistor = persistStore(store);
return { persistor, store };
}
todo reducer 没有问题,但我重新创建了一个额外的提醒 reducer 来复制并查看问题是否仍然存在并且结果相同。