我正在尝试使用'comments'对象实现一个reducer,该对象包含一些ID索引的注释数组。我想合并而不是替换'comments'对象中的属性。
现在我有这个:
commentsReducer {
comments: {}
1: Array[9]
2: Array[5]
isFetchingComments: true
lastUpdated: null
}
我的减速机功能:
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
}
答案 0 :(得分:3)
更改
var new_cm = {comments:{[action.pid]: action.comments}};
它应该做的伎俩
修改强>
如果您想添加更多评论,那么
var new_cm = {comments: Object.assign({}, state.comments, {[action.pid]: action.comments})};
答案 1 :(得分:0)
尝试jQuery的功能:
$.extend();
var obj1 = {
a: 1,
b: 2
};
var obj2 = {
b:3,
c:4
};
var obj3 = $.extend({},obj1,obj2);
console.info(obj3);
结果是: { 答:1, B:3, C:4- }
希望这对你有用......
答案 2 :(得分:0)
你可以试试这个。
switch(action.type){
case RECEIVE_COMMENTS:
var new_cm = Object.assign({}, state.comments, {[action.pid]: action.comments});
return Object.assign({}, state, new_cm);
}