javascript - 嵌套动作使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 存储中看到它,如果在添加它的同一会话期间记录它,它也会作为一个空数组出现。假设我添加了一个数字,然后重新加载应用程序,然后记录状态。这次它将正确显示其中的数字。
解决方案
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,
});
};
};
推荐阅读
- box-api - 在 Box 中上传批量图像
- react-native - 如果文本输入为空字符串,则在设备上反应本机禁用提交键盘
- javascript - React Native - 如何舍入动画组件的值?
- xml - 使用包含多种类型的 XSLT 解析字符串
- ruby - Ruby Net::SSH 重用会话
- c++ - 为什么 GCC 8.2 编译在软浮点源期间抛出错误?
- python - SQLAlchemy Harvesine 大圆计算错误
- javascript - 使用 Vue.js:当没有“下一张”照片可用时,禁用图片幻灯片上的按钮
- javascript - 未捕获的类型错误:无法读取 null 的属性“隐藏”
- c++ - 2048 - 如何阻止我的图块合并两次?