Redux 在另一个 reducer 中更新状态
Redux updating state in another reducer
设置
在我的应用程序中,我有分配家庭作业的学生。每次 创建一个学生时 我循环遍历当前作业并为每个学生更新作业数组。
我的问题是当我创建作业 时。不仅必须创建作业,而且创建后我还需要将其分配给特定的学生。
我已将我的应用程序拆分为三个减速器; 类、学生和家庭作业。
问题
如何从 Homework reducer 更新我的学生状态?我需要等到作业被创建,然后在每个学生中分配作业数组。也许我可以分派一个动作,然后分派另一个动作?
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 中生成随机 GUID,因此相同的输入永远不会给出相同的输出。如果你要将 GUID 生成移动到你的操作中,你可以将它传递到你的 CREATEHOMEWORK
操作的有效负载中,然后在你的 students
reducer 处理的 ASSIGNHOMEWORK
操作中分派它.
设置
在我的应用程序中,我有分配家庭作业的学生。每次 创建一个学生时 我循环遍历当前作业并为每个学生更新作业数组。
我的问题是当我创建作业 时。不仅必须创建作业,而且创建后我还需要将其分配给特定的学生。
我已将我的应用程序拆分为三个减速器; 类、学生和家庭作业。
问题
如何从 Homework reducer 更新我的学生状态?我需要等到作业被创建,然后在每个学生中分配作业数组。也许我可以分派一个动作,然后分派另一个动作?
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 中生成随机 GUID,因此相同的输入永远不会给出相同的输出。如果你要将 GUID 生成移动到你的操作中,你可以将它传递到你的 CREATEHOMEWORK
操作的有效负载中,然后在你的 students
reducer 处理的 ASSIGNHOMEWORK
操作中分派它.