代码之家  ›  专栏  ›  技术社区  ›  TiagoM

在我的react redux reducer的任何操作之后更新数组的状态

  •  0
  • TiagoM  · 技术社区  · 5 年前

    我现在正在学习react redux,已经掌握了基本知识(我相信),我现在正在尝试在我的状态上创建一个可以由多个操作填充的通知数组。

    我考虑过使用中间件类,但这会在reduce上计算操作之前将通知添加到数组中。

    快速示例:

    用户添加项目->分派操作->影响与项目相关的状态属性->在通知数组中添加通知

    这是两个不同的操作,我可以在if逻辑中的每个操作(在reducer上)更新通知数组,但看起来像重复的代码,我会在reducer上创建通知对象,可以吗?

    那么在这种情况下,我应该在哪里分派向通知数组添加通知的操作呢?

    我在寻找最佳实践

    1 回复  |  直到 5 年前
        1
  •  1
  •   Muhammad Zeeshan    5 年前

    最佳实践是处理这样的场景 reducer . 一次性处理数据并相应地更新状态。在您的场景中,您希望更新 notifications 一次数组 action

    case LOGIN:
      //checks if user is valid
      return {
         ...state
         loggedIn: true,
         user,
         notifications: state.notification.push({ id: 1, message: "Logged In!" })
      }
    

    如果你想移除 notification 你可以这样做:

    case REMOVE_NOTIFICATION:
      // You can get the notification ID you want to remove from action
      let notifications = state.notification.filter(notify => notify.id !== action.id);
      return {
         ...state
         notifications
      }