【问题标题】:How to merge object properties inside an object belonging to a Reducer如何在属于 Reducer 的对象内合并对象属性
【发布时间】:2015-11-13 02:57:52
【问题描述】:

我正在尝试使用“cmets”对象实现一个reducer,该对象包含由某个ID 索引的cmets 数组。我想合并而不是替换“cmets”对象中的属性。

现在我有这个:

commentsReducer {
   comments: {}
   1: Array[9]
   2: Array[5]
   isFetchingComments: true
   lastUpdated: null
}

我的 Reducer 函数:

function commentsReducer(state = {
   isFetchingComments: false,
   lastUpdated: null,
   comments : {}
   },action){

  switch(action.type){      
    case RECEIVE_COMMENTS:
      var new_cm = {[action.pid]: action.comments};
      return Object.assign({}, state, new_cm); 

  }
}

我正在尝试做的事情:

commentsReducer {
   comments { 
      1: Array[9],
      2: Array[5]
   }
   isFetchingComments: true
   lastUpdated: null
}

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    改变

    var new_cm = {comments:{[action.pid]: action.comments}};
    

    它应该可以解决问题

    编辑

    如果你想添加更多的 cmets 那么

    var new_cm = {comments: Object.assign({}, state.comments, {[action.pid]: action.comments})};
    

    【讨论】:

    • 这样替换了 cmets 属性。
    • 我以为你想用新的 cmets 替换 cmets 属性
    • 第二种解决方案有一些奇怪的行为。它改变了 cmets 之外的属性。我想我会选择第一个解决方案,尽管它取代了属性。
    • @JoãoLima Opps 你是对的,我忘记了一些东西,在新的编辑中更新了 - 现在应该可以工作了。
    • 按预期工作。非常感谢。
    【解决方案2】:

    试试 jQuery 的功能: $.extend();


    示例:

    var obj1 = {
      a: 1,
      b: 2
    };
    var obj2 = {
       b:3,
       c:4
    };
    var obj3 = $.extend({},obj1,obj2);
    console.info(obj3);
    

    结果是: { 一个:1, 乙:3, c:4 }


    希望这对你有用...

    【讨论】:

      【解决方案3】:

      你可以试试这个。

      switch(action.type){      
        case RECEIVE_COMMENTS:
          var new_cm = Object.assign({}, state.comments, {[action.pid]: action.comments});
          return Object.assign({}, state, new_cm); 
      
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-18
        • 1970-01-01
        • 2015-09-23
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多