【问题标题】:Applying a wrapper function to an imported function将包装函数应用于导入的函数
【发布时间】:2018-06-25 12:03:55
【问题描述】:

所以我在使用 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

【问题讨论】:

    标签: javascript ecmascript-6 immutable.js


    【解决方案1】:

    根据您的链接示例,您应该在模型上调用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));
    

    【讨论】:

    • 是的,我之前确实尝试过,但它给了我这个错误TypeError: __WEBPACK_IMPORTED_MODULE_8__records__.a.fromJS is not a function
    猜你喜欢
    • 2014-11-07
    • 2022-07-08
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多