【问题标题】:Immutable js updating a Map in a List不可变 js 更新列表中的地图
【发布时间】:2016-05-13 19:55:41
【问题描述】:

将嵌套数据推入 List 内的 Map

谁能告诉我:
理想情况下,我如何通过特定的用户 ID 将任务推送给这些用户(列表项)?

提前致谢。

我的代码:

const initialState = Immutable.List([
  Immutable.Map({
    "id": 1,
    "name": "Abe Bell",
    "tasks": [
      {
        "id": 1,
        "title": "Get haircut",
        "status": false
      }
    ]
  }),
  Immutable.Map({
    "id": 2,
    "name": "Chad Dim",
    "tasks": [
      {
        "id": 2,
        "title": "Get real job",
        "status": false
      }
    ]
  })
])

【问题讨论】:

  • 你的州有这样的结构吗?在我看来,您可以将其简化为只使用地图。尽管完全可以编辑当前结构,但它不必要地复杂。作为一般规则,出于性能/简单性的原因,尽可能选择地图而不是列表。

标签: immutability immutable.js


【解决方案1】:

首先,您构建此结构的方式,tasks 数组不会是不可变实例,我认为这不是您想要的,您可以使用Immutable.fromJS 将所有嵌套数组和映射转换为一个不可变的实例。

根据您的数据结构方式,您必须浏览用户列表并在 id 匹配时执行更新。

一种方法是使用map

const initialState = Immutable.fromJS([
  {
    "id": 1,
    "name": "Abe Bell",
    "tasks": [
      {
        "id": 1,
        "title": "Get haircut",
        "status": false
      }
    ]
   },
   {
    "id": 2,
    "name": "Chad Dim",
    "tasks": [
      {
        "id": 2,
        "title": "Get real job",
        "status": false
      }
    ]
  }
]);

let userId = 2;

let newState = initialState.map(user => {
    if (user.get('id') !== userId) {
    return user;
  }
  return user.update('tasks', tasks => {    
    return tasks.push(Immutable.fromJS({
      id: 3,
      title: "new task",
      status: false
    }))
  });
});

虽然这可以满足您的需求,但我认为如果这种操作在您的应用程序中经常出现,您应该将数据更改为地图而不是列表。这将使事情变得更容易和更快。

const initialState = Immutable.fromJS({
  "1": {
    "id": 1,
    "name": "Abe Bell",
    "tasks": [
      {
        "id": 1,
        "title": "Get haircut",
        "status": false
      }
    ]
   },
   "2": {
    "id": 2,
    "name": "Chad Dim",
    "tasks": [
      {
        "id": 2,
        "title": "Get real job",
        "status": false
      }
    ]
  }
});

let userId = "2";

let newState = initialState.updateIn([userId, 'tasks'], tasks => {
  return tasks.push(Immutable.fromJS({
    id: 3,
    title: "new task",
    status: false
  }));
});

【讨论】:

    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    相关资源
    最近更新 更多