【问题标题】:update name from the list using immutablejs使用 immutablejs 从列表中更新名称
【发布时间】:2017-01-05 12:02:48
【问题描述】:

我很难理解 immutablejs 的文档。我想更新名称为 Sanskar 的列表。为此,我首先尝试使用 findIndex 查找其索引并使用 update() 对其进行更新。但我收到 item.get() is not a function 的错误。

为什么我收到 item.get is not a function 的错误?

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中练习immutablejs

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

【问题讨论】:

    标签: javascript ecmascript-6 immutable.js


    【解决方案1】:

    请参阅下面的代码,了解如何做你想做的事。第一个问题是您没有正确构建列表,第二个问题是您更新相关元素的方式。

    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());
    

    【讨论】:

    • NP!很高兴它有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多