不可变js更新列表中的地图
Immutable js updating a Map in a List
将嵌套数据推送到列表中的地图中
谁能告诉我:
我如何理想地通过特定用户 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
}
]
})
])
首先,你构建这个结构的方式,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
}));
});
将嵌套数据推送到列表中的地图中
谁能告诉我:
我如何理想地通过特定用户 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
}
]
})
])
首先,你构建这个结构的方式,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
}));
});