2017-01-05 47 views
0

我很难理解immutablejs的文档。我想更新名字是Sanskar的名单。为此,我首先尝试使用findIndex来查找其索引并使用update()更新它。但我得到一个错误item.get()不是一个函数。使用immutablejs更新列表名称

为什么我得到一个item.get的错误不是函数?

const arr = [ 
      {name: 'Sanskar', age: 24, designation: 'Intern Developer'}, 
      {name: 'John', age: 28, designation: 'Developer'} 
      ]; 
const list1 = Immutable.List.of(arr); 

const list2 = list1.findIndex(item => item.get('name') === 'Sanskar'); 
console.log('list2', list2.toJS()); 

我在jsbin

http://jsbin.com/zawinecutu/edit?js,console

回答

1

请参阅下面的代码怎么做你想做的事为例练immutablejs。第一个问题是你没有正确地构建你的List,第二个问题是你更新有问题的元素的方式。

const Immutable = require('immutable'); 
const arr = [ 
      {name: 'Sanskar', age: 24, designation: 'Intern Developer'}, 
      {name: 'John', age: 28, designation: 'Developer'} 
      ]; 

// your initial data is an array of objects. If you want a List of objects: 
const list1 = Immutable.List.of(...arr); 

// the contents of the list are ordinary JavaScript objects. 
const person2Index = list1.findIndex(item => item['name'] === 'Sanskar'); 

// now you can use the List.get() method: 
const person2 = list1.get(person2Index); 

person2['designation'] = 'Astronaut'; 

// do the update like this 
const list2 = list1.update(person2Index, p => person2); 

console.log(list2.toJS()); 
+0

谢谢你让我现在明白了。 – Serenity

+1

NP!很高兴帮助。 –