设置
在我的应用程序中,我有分配家庭作业的学生。每次创建学生时,我都会遍历当前作业并为每个学生更新作业数组。
我的问题是当我创建作业时。不仅必须创建作业,而且我还需要在创建作业后将其分配给特定的学生。
我已将我的应用程序拆分为三个 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
最佳答案
你的 reducer 应该是一个纯函数——也就是说,给定相同的输入,它总是会产生相同的输出。您在 reducer 中生成随机 GUID,因此相同的输入永远不会给出相同的输出。如果您要将 GUID 生成移动到您的操作中,您可以将它传递到您的 CREATEHOMEWORK
操作的有效负载中,然后在 ASSIGNHOMEWORK
操作中分派(dispatch)它,您的 students
reducer handles.
关于javascript - Redux 在另一个 reducer 中更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710410/