首页 > 解决方案 > 嵌套动作使reducer状态与redux store不同?

问题描述

我有一个问题,我的 redux 商店与我的减速器中的状态不同。这个问题与我如何称呼我的行为有关。我的目标是获取更新的状态,以便我可以在减速器中针对不同的情况(例如state.numbers)调用它。我在按下按钮时调用一个动作。这个动作的属性会被发送到不同的reducer,然后调用一个函数(这个函数调度导致问题的动作)。

这是按下按钮时调用的动作:

export const startReminder = (item) => {
  return (dispatch) => {
    dispatch({ //this dispatch works great and isn't the issue
      type: START_REMINDER,
      id: item.id
    });
    scheduleNotification.startReminder(item); //the issue is this function right here
  };
};

这个函数我将简化为这个,因为它重现了这个问题:

export const scheduleNotification = {
  async startReminder() {
    store.dispatch(testing(1));
  }
};

发送的测试操作如下所示:

export const testing = (number) => {
  return {
    type: 'testing',
    number
  };
};

然后在我的减速器中,我按下一个不同的按钮,触发一个案例记录state.numbers。如果我在添加了一个数字(或多个)的同一会话中触发此案例,它们将不会被记录。但是如果我重新加载会话然后让状态记录它(我保存数据),它会正确地将它记录到控制台。我尝试将这个分派的动作从开始提醒中移出,并解决了这个问题。因此,它与在辅助函数中被调用有关,在另一个动作中被调用。

我希望我可以移动它,但它不是那么简单。在 scheduleNotification 函数中,我获得了需要存储在商店中的唯一 ID。在我拥有该 ID 之前,我无法发送操作。如果有人知道出了什么问题或有任何建议,我将不胜感激,我不知道是什么导致了这个问题。

举个例子,假设我的 numbers 数组为空,然后我向其中添加了一个数字。即使我在 redux 存储中看到它,如果在添加它的同一会话期间记录它,它也会作为一个空数组出现。假设我添加了一个数字,然后重新加载应用程序,然后记录状态。这次它将正确显示其中的数字。

标签: javascriptreactjsreact-nativeredux

解决方案


export const startReminder = (item) => {
  return async (dispatch) => {
    dispatch({
      type: START_REMINDER,
      id: item.id
    });

    // This is where the request to your backend happens.
    // startReminder needs to return a promise or be async itself
    const number = await scheduleNotification.startReminder(item);

    // Since a request can fail, you would normally have error handling here,
    // like a try {} catch {} block, but I left that out for the sake of simplicity.

    dispatch({
        type: 'testing',
        number,
    });
  };
};

推荐阅读