【问题标题】:Redux updating state in another reducerRedux 在另一个 reducer 中更新状态
【发布时间】:2018-11-15 13:11:39
【问题描述】:

设置

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

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

我已将我的应用程序拆分为三个减速器;班级、学生和家庭作业。

问题

如何从 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

【问题讨论】:

标签: javascript reactjs redux reducers


【解决方案1】:

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

【讨论】:

  • 这很有效,通过将日期和 guid 作为有效负载的一部分,我能够向两个减速器发送相同的操作。非常感谢
猜你喜欢
  • 2019-07-28
  • 2018-01-02
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 2016-12-01
  • 2021-01-08
  • 2019-04-01
  • 2017-04-02
相关资源
最近更新 更多