简体   繁体   English

合并两个具有内部数组属性的对象,而不会在react中改变状态

[英]Merging two objects with inner array properties without mutating the state in react

I have got a state object like so : 我有一个这样的状态对象:

{
    news: {
        news: [
            {
                id: 1,
                name: 'test1'
            },
            {
                id: 2,
                name: 'test2'
            },
            {
                id: 3,
                name: 'test3'
            }
        ]
    }
    ]
}

Now, I am making an Ajax request and getting my response like so: 现在,我正在发出一个Ajax请求,并得到如下响应:

[
    {
        id: 4,
        name: 'test4'   
    },
    {
        id: 5,
        name: 'test5'   
    },
    {
        id: 6,
        name: 'test6'   
    }
]

I dont want to mutate the state, so in my Reducer, how do I merge the two values so that the final output is like so: 我不想改变状态,因此在我的Reducer中,如何合并两个值,以便最终输出像这样:

{
    news: {
        news: [
            {
                id: 1,
                name: 'test1'
            },
            {
                id: 2,
                name: 'test2'
            },
            {
                id: 3,
                name: 'test3'
            },
            {
                id: 4,
                name: 'test4'   
            },
            {
                id: 5,
                name: 'test5'   
            },
            {
                id: 6,
                name: 'test6'   
            }
        ]
    }
    ]
}

I tried something like this, however, it replaced the entire news object. 我尝试过类似的方法,但是它代替了整个新闻对象。

return { ...state, news: action.payload }

Where action.payload has the values that I am getting in my response. 其中action.payload具有我在响应中获得的值。 I know I might be missing something simple and obvious in this. 我知道我可能会错过一些简单而明显的东西。

假设action.payload是ajax返回的news数组:

return { ...state, news: { news: [...state.news.news, ...action.payload] } }

This is a helper function that will do a deep clone for you regardless of the structure: 这是一个辅助函数,无论结构如何,它都会为您做深层克隆:

function deepClone(obj){
    return Object.keys(obj).reduce((objClone, key) => {
        let newValue;

        if(Array.isArray(obj[key]){
            newValue = obj[key].map(item => deepClone(item));
        }
        else if(obj[key] !== null && typeof obj[key] = 'object'){
            newValue = deepclone(obj[key]);
        }
        else{
            newvalue = obj[key];
        }

        return {...copyObj, [key]: newvalue};
    }, {});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM