javascript - Redux 在另一个 reducer 中更新状态

标签 javascript reactjs redux reducers

设置

在我的应用程序中,我有分配家庭作业的学生。每次创建学生时,我都会遍历当前作业并为每个学生更新作业数组。

我的问题是当我创建作业时。不仅必须创建作业,而且我还需要在创建作业后将其分配给特定的学生。

我已将我的应用程序拆分为三个 reducer ;类(class)、学生和家庭作业。

问题

如何从 Homework reducer 更新我的学生状态?我需要等到作业被创建,然后在每个学生中分配作业数组。也许我可以分派(dispatch)一个 Action ,然后分派(dispatch)另一个 Action ?

case actionTypes.CREATEHOMEWORKS:
    // Get new homework description
    const newHomework = action.newHomework
    // Get the currently active class
    const activeClass = action.activeClass.key;
    // Get users current browser data
    const dateCreated = getCurrentDate();
    // Generare a new UID
    const key = guid();
    // Create a new homework object
    const homework = { key: key, class: activeClass, dateCreated: dateCreated, description: newHomework };
    // Get the current homework array
    const homeworks = JSON.parse(JSON.stringify(state.homeworks));
    // Combine current homework with new homework object.
    homeworks.push(homework);
    
    // I now need to update students to have this homework but they are handled
    // in another state

enter image description here

最佳答案

你的 reducer 应该是一个纯函数——也就是说,给定相同的输入,它总是会产生相同的输出。您在 reducer 中生成随机 GUID,因此相同的输入永远不会给出相同的输出。如果您要将 GUID 生成移动到您的操作中,您可以将它传递到您的 CREATEHOMEWORK 操作的有效负载中,然后在 ASSIGNHOMEWORK 操作中分派(dispatch)它,您的 students reducer handles.

关于javascript - Redux 在另一个 reducer 中更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710410/

相关文章:

reactjs - React 使用 useEffect Hook 分页 - 如果请求失败,如何恢复页码?

javascript - 如何使用 Bootstrap 在 React 中显示模态对话框

javascript - React Router v4 中的 indexLink

javascript - 为什么我要使用 Redux Promise 中间件而不是 Redux Promise?

javascript - 添加 Ajax 内容后单击事件不工作

javascript - require() 的顺序似乎会影响模块

node.js - 如何用 fetch api 正确替换 axios api 并映射到 nodeJS 中接收到的数据?

Redux – 依赖于其他状态的 Reducer

javascript - 如何从 yaml 文件为 Kubernetes Nodejs API 客户端生成 `V1Job` 对象?

javascript - jQuery - 尝试隐藏框架内的元素