如何持久化变径器,以便我可以从中找到唯一的对象?

时间:2019-11-15 19:53:20

标签: reactjs react-native redux

我正在为用户建立取消预定通知的功能。每个通知都有一个唯一的ID,我需要找到该ID才能将其取消。它们以一种称为notificationID的状态存储在我的提醒还原器中,另外还有两个用于唯一标识对象的属性。

当用户尝试取消通知时,我会找到带有唯一标识符的notificationID。这是问题开始的地方。有时notificationID在那儿,有时不是。即使在寻找状态时看到我正在寻找的对象,它也会返回未定义的状态。状态块还会随机删除自身,并返回到无内容,而不是继续存在。

我不确定问题出在减速器的持久性还是减速器本身,我的直觉是这是两者的结合。

我的redux商店:

const remindersPersistConfig = {
  key: 'remindersreducer',
  storage: AsyncStorage,
  whitelist: ['notificationIDs'],
  stateReconciler: autoMergeLevel2
};

const rootPersistConfig = {
  key: 'root',
  storage: AsyncStorage,
  whitelist: ['TodoReducer', 'RemindersReducer'],
  stateReconciler: autoMergeLevel2
};

const reducers = combineReducers({
  ModalReducer,
  TodoReducer: persistReducer(todoPersistConfig, TodoReducer),
  RemindersReducer: persistReducer(remindersPersistConfig, RemindersReducer),
  AuthReducer
});

const persistedReducer = persistReducer(rootPersistConfig, reducers);

export default function storeConfiguration() {
  const store = createStore(
    persistedReducer,
    {},
    composeEnhancers(
      applyMiddleware(ReduxThunk)
    )
  );

  const persistor = persistStore(store);

  return { persistor, store };
}

我的添加和取消通知操作:

export const addNotifiactionID = (item, reminderType, notificationID) => {
  return {
    type: ADD_NOTIFICATION_ID,
    notificationID,
    item,
    reminderType
  };
};

export const cancelNotification = (item, reminderType) => {
  return {
    type: CANCEL_NOTIFICATION,
    id: item.id,
    reminderType
  };
};

负责获取信息并查找notificationID的reduce:

const initialState = {
  notificationIDs: []
};

export default (state = initialState, action) => {
  switch (action.type) {
    case PERSIST_REHYDRATE:
      return action.payload.RemindersReducer || [];
    case ADD_NOTIFICATION_ID:
      return { ...state,
        notificationIDs: [...state.notificationIDs,
        {
          itemID: action.item.id,
          reminderType: action.reminderType,
          notificationID: action.notificationID
        }]
      };
    case CANCEL_NOTIFICATION: {
      console.log(state.notificationIDs);
      const notificationData = state.notificationIDs.find(
        item => (item.itemID === action.id && item.reminderType === action.reminderType)
      ); //issue is redux notificationIDs randomly dissapear from reducer
      console.log(notificationData);
      //Notifications.cancelScheduledNotificationAsync(notificationData.notificationID);
      return;
    }
    default:
      return state;
  }
};

我的控制台日志显示提醒在那儿,然后notificationData有时返回未定义的状态,有时它将按应有的方式工作,并且即使我未删除任何状态,notificationID中也没有任何内容。

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

在您的CANCEL_NOTIFICATION减速器中,您似乎未返回任何状态。可能是数据丢失的原因。

SAVE