【问题标题】:how to use Immutable.js with ES6 classes?如何在 ES6 类中使用 Immutable.js?
【发布时间】:2017-04-26 18:04:30
【问题描述】:

以下代码:

class A {constructor(v) {
    this.v = v;
}}
const a = fromJS(new A({a: 42, someOtherSubTree: {}}));
const aMod = a.updateIn(['v', 'a'], x=>43);

... 失败:

TypeError: a.updateIn is not a function

更简单的set 也失败了:

TypeError: a.set is not a function

我发现 this related question 被标记为“打字稿”,所以我不确定那里建议的“包装”方法如何转化为纯 ES6。

【问题讨论】:

标签: javascript immutable.js


【解决方案1】:

const a = fromJS(new A({a: 42, someOtherSubTree: {}})); 之后,typeof a 仍然是一个对象,Map 就像预期的那样。它返回原始对象。

不可变代码中的这一部分说明了原因。因为您的对象 A 不是“普通对象”(参见函数)也不是数组,所以它只是按原样返回。

function fromJSDefault(json) {
    if (Array.isArray(json)) {
      return IndexedSeq(json).map(fromJSDefault).toList();
    }
    if (isPlainObj(json)) {
      return KeyedSeq(json).map(fromJSDefault).toMap();
    }
    return json;
}
// […]
function isPlainObj(value) {
    return value && (value.constructor === Object || value.constructor === undefined);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2016-11-11
    • 2018-03-08
    • 2017-05-25
    • 2019-03-13
    • 2020-10-19
    相关资源
    最近更新 更多