Reactjs不可变状态为Mutable

时间:2018-05-27 06:10:47

标签: reactjs react-redux immutable.js

我们有这个州:

import {Map, Record} from 'immutable';


export interface State {
  _id?: string;
  data: Map<string, any>;
  error: Error;
  loading: boolean;
}


export const iDSS: State = {
  _id: null,
  data: Map({}),
  error: null,
  loading: false
};


export class DatasourceState extends Record(iDSS) {

  constructor(params: State) {
    super(params);
  }

  get<T extends keyof State>(key: T): State[T] {
    return super.get(key);
  }

  set<T extends keyof State, V extends keyof State>(key: T, value: State[V]) {
    return super.set(key, value);
  }

}

我们要求在状态中设置动态密钥,但由于不变性而导致跟随错误:

Cannot set unknown key "widget-test-2" on DatasourceState

DatasourceState已在应用中的多个位置使用过。是否有任何简单的方法可以使DatasourceState变为可变,而无需更改其余的实现。基本上 - 我们正在寻找一个可变的Record

1 个答案:

答案 0 :(得分:0)

你总是可以在任何immutablejs记录上调用.toJS()来获取js对象

https://facebook.github.io/immutable-js/docs/#/Record/toJS

同时检查toObject()

https://facebook.github.io/immutable-js/docs/#/Record/toObject