如何在 immutable.js 列表中使用 setIn
How to use setIn with immutable.js List
好的,我有一个对象列表,非常标准。
const list = Immutable.List([{type:'thang',data:{id:'pants'}}]);
现在我想把裤子换成短裤...所以我在想
list.setIn([0,'data','id'],'shorts');
唉
Error: invalid keyPath
这是怎么做到的?
尽管弄乱了一段时间,我什至无法做到这一点:/一旦我知道如何做到这一点,我想知道如何在某个位置添加新元素
list.setIn([0,'data','length'],'short');
将新的长度属性添加到列表中位置 0 的数据对象。
我的错。我在创建不可变结构时出错了。如果我改变
const list = Immutable.List([{type:'thang',data:{id:'pants'}}]);
到
const list = Immutable.fromJS([{type:'thang',data:{id:'pants'}}]);
那我可以
list.setIn([0,'data','id'],'shorts');
我们的嵌套结构化数据:
const state = {
Persons: [
{
fname: 'J.R.R',
lname: 'Tolkin',
},
{
fname: 'jack',
lname: 'London',
}
]
};
要求不可变
const { fromJS } = require('immutable')
将简单对象转为地图
const stateMapped = fromJS(state);
从嵌套结构获取数据
console.log(stateMapped.getIn(['Persons', 0, 'fname']))//output: J.R.R
在嵌套结构中设置数据
var objClone = stateMapped.setIn(['Persons', '0', 'fname'], 'John Ronald Reuel');
console.log('' + objClone.getIn(['Persons', 0, 'fname'])); //output: John Ronald Reuel
好的,我有一个对象列表,非常标准。
const list = Immutable.List([{type:'thang',data:{id:'pants'}}]);
现在我想把裤子换成短裤...所以我在想
list.setIn([0,'data','id'],'shorts');
唉
Error: invalid keyPath
这是怎么做到的?
尽管弄乱了一段时间,我什至无法做到这一点:/一旦我知道如何做到这一点,我想知道如何在某个位置添加新元素
list.setIn([0,'data','length'],'short');
将新的长度属性添加到列表中位置 0 的数据对象。
我的错。我在创建不可变结构时出错了。如果我改变
const list = Immutable.List([{type:'thang',data:{id:'pants'}}]);
到
const list = Immutable.fromJS([{type:'thang',data:{id:'pants'}}]);
那我可以
list.setIn([0,'data','id'],'shorts');
我们的嵌套结构化数据:
const state = {
Persons: [
{
fname: 'J.R.R',
lname: 'Tolkin',
},
{
fname: 'jack',
lname: 'London',
}
]
};
要求不可变
const { fromJS } = require('immutable')
将简单对象转为地图
const stateMapped = fromJS(state);
从嵌套结构获取数据
console.log(stateMapped.getIn(['Persons', 0, 'fname']))//output: J.R.R
在嵌套结构中设置数据
var objClone = stateMapped.setIn(['Persons', '0', 'fname'], 'John Ronald Reuel');
console.log('' + objClone.getIn(['Persons', 0, 'fname'])); //output: John Ronald Reuel