Immutable.js没有redux,如何在不明确命名的情况下创建新列表?

时间:2016-08-20 14:49:21

标签: immutable.js

--- ---背景
我正在尝试学习当前最好的数据管理实践,据我所知,这意味着无状态 / 有状态 组件不可变数据结构。我在实现后者(immutables)方面遇到了问题。我正试图将它合并到角度2而不用redux。 Redux是我要学习的东西的列表,但是现在我想使用不带redux的immutable.js。

---问题---
如何在服务中创建数组副本并按需返回?我有这个示例代码(仅用于插图目的,我还没有测试过它!):

import { Product } from './product';
import { Immutable } from './immutable';

export class ProductListService {
    let id = 0;

    const cheese  = new Product(id++, 'cheese');
    const ham  = new Product(id++, 'ham');
    const milk = new Product(id++, 'milk');

    // I fill the list with some sample data
    let oldProductList = Immutable.List.of(cheese, ham, milk);
    let newProductList = [];
    let returnProductList = oldProductList;

    getProductList() {
        return returnProductList;
    }

    addProduct() {
        // As far as I know, this creates a deep immutable copy
        newProductList = oldProductList.withMutations(function (list) {
            list.push(new Product(id++, 'name'););
        });
        returnProductList = newProductList;
        oldProductList = newProductList;
    }
}

上面的代码基于官方文档中的示例,他们只是在每次创建副本时向变量添加一个数字(我明白这只是为了示例目的?)。如何在不使用数字的情况下创建新列表?我使用oldList / newList吗?我是否为新变量动态创建新数字,以便我有对象的历史记录?

我觉得我在建筑层面做错了。什么是正确的方法?所有immutable.js示例都使用redux或者没有显示现实生活中的例子,是否有人知道有关immutalbe.js的好材料(+可能的ng2?)

由于

1 个答案:

答案 0 :(得分:0)

我不确定我完全明白你想做什么, 但请考虑一下:如果您只想将一个元素推送到列表,则不应使用withMutations

let list1 = Immutable.List(['one'])
let list2 = list1.push('two')
console.log(list1.toJS()) // ['one']
console.log(list2.toJS()) // ['one', 'two']

应用变异来创建新的不可变对象会导致一些开销,这可能会导致轻微的性能损失。仅使用withMutations如果您需要在返回之前在本地应用一系列突变

let list1 = Immutable.List(['one'])
var list2 = list1.withMutations(function (list) {
  list.push('two').push('three').push('four').push('five');
});
console.log(list1.toJS()) //["one"]
console.log(list2.toJS()) //["one", "two", "three", "four", "five"]

这里我们创建一个列表1的临时可变(瞬态)副本,并使用withMutations以高效的方式应用一批突变

我希望能回答你的问题