将包装函数应用于导入的函数

时间:2018-01-16 17:44:44

标签: javascript ecmascript-6 immutable.js

所以我在使用Immutable.js嵌套报告访问数据时遇到问题。

我似乎在by AndrewBestbier找到了一个解决方案,但实际上我将它应用到我的代码中时遇到了麻烦。

解决方案说,fromJS()来自immutable.js的导入函数接受“reviver”函数。然后它继续提供某种包装函数:

Record.constructor.prototype.fromJS = function(values) {
  var nested = fromJS(values, function(key, value){
    //See https://facebook.github.io/immutable-js/docs/#/fromJS for docs on custom reviver functions
    if(this.prototype[key] && this.prototype[key].constructor.prototype instanceof Record){
      return this.prototype[key].constructor.fromJS(value.toJS()); //use toJS() here if nest more than once
    }
    else {
      return value;
    }
  }.bind(this));
  console.log()
  return this(nested);
};

我不确定我是如何将其应用到我的代码中的:

import { fromJS, mergeDeep, OrderedMap, Record } from 'immutable'

// Putting the suggested function here doesn't seem to do anything
// I must be missing some steps to get fromJS() to work with this 
// wrapper code.

const mergeEntities = (state, payload) => {
  return state.merge(payload.map( (id) => new Entity(id) ))
}

return mergeEntities(state, fromJS(action.payload.entities));

如果有人能指出我正确的方向,那就太好了!

修改

以下是我导出的记录文件的摘录:

const EntityRecord = new Record({
  id: undefined,
  status: "",
  messages: new Message(),
  redirectTo: "",
  entityType: "",
  isFetching: undefined,
  lang: "",
  title: "",
  charset: "",
  viewport: "",
  description: "",
  keywords: "",
  forms: new Form(),
  socialLoginText: "",
  forgotPasswordLinkText: "",
  registerLinkText: ""
});

class Entity extends EntityRecord{

}

export default Entity

1 个答案:

答案 0 :(得分:0)

根据您链接的示例,您需要直接调用模型上的fromJS方法而不是fromJS函数。我对immutable.js并不熟悉,但假设您的Entity来自Record类,我认为它看起来像这样:

import { fromJS, mergeDeep, OrderedMap, Record } from 'immutable'

Record.constructor.prototype.fromJS = function(values) {
  var nested = fromJS(values, function(key, value){
    //See https://facebook.github.io/immutable-js/docs/#/fromJS for docs on custom reviver functions
    if(this.prototype[key] && this.prototype[key].constructor.prototype instanceof Record){
      return this.prototype[key].constructor.fromJS(value.toJS()); //use toJS() here if nest more than once
    }
    else {
      return value;
    }
  }.bind(this));
  console.log()
  return this(nested);
};

const mergeEntities = (state, payload) => {
  return state.merge(payload.map( (id) => new Entity(id) ))
}

return mergeEntities(state, Entity.fromJS(action.payload.entities));