代码之家  ›  专栏  ›  技术社区  ›  Erdal SATIK

不可变JS-Redux Saga按键查找项并更新值

  •  0
  • Erdal SATIK  · 技术社区  · 7 年前

    我在我的React应用程序中使用Redux Saga和Immutable.js。 我有通知数组,它保存由整个应用程序的redux操作创建的每个通知的数据。

    我的不可变redux存储和通知数组如下所示:

    global : 
      notifications: 
       0:
        key: 21339298 // random key to use like id
        show: true
        type: success
        message: Operation was successfull
       1: {key..., show...}
       ...
    

    我想通过“key”找到单个通知,并将其“show”值更新为false。

    我阅读了不可变的.js文档,但很难理解。 所以我尝试了下面的代码片段。但我没有得到结果。

    return state
        .updateIn(['notifications', 
            ns => ns.findIndex(function (item) {
                return item.get("key") === action.notificationId;}
            ), 'show'], false
        );
    
    return state
        .update(
            list.findIndex(function (item) {
                return item.get("key") === action.notificationId;
            }), function (item) {
                return item.set("show", false);
            }
        );
    

    如何查找项目并更新其某些值?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Erdal SATIK    7 年前

    解决方案是分离查找索引和更新,首先查找索引,然后将其与 setIn . 下面是解决方案。

    case NOTIFY_HIDE:
            let notifications = state.get('notifications');
            let notificationIdx = notifications.findIndex(function (item) {
                return item.get('key') === action.notificationId;
            });
            return state
                .setIn(['notifications', notificationIdx, 'show'], false);