简体   繁体   中英

How to append an array to an array in Redux reducer?

Say I have the following condition in the reducer:

    case POST_LOAD_SUCCESS:
        return {
            ...state,
            posts: [...payload]
        }

This action contains an array as payload [{post_1},{post_2},{post_3},{post4},{post5}] . Now if this action is fired again what happens is that the previous payload is replaced by the new one, which is correct behavior.
What I want to do is to append the next call into the previous posts array: So say if the post array is already the following:

posts: [
    {post_1},
    {post_2},
    {post_3},
    {post_4},
    {post_5}
];

Now as more data arrives I want that new data to be appended to this post again (no matter the size, by this I mean that if the new array does not contain 5 elements):

posts: [
    {post_1},
    {post_2},
    {post_3},
    {post_4},
    {post_5},
    {post_6},
    {post_7},
    {post_8},
    {post_9},
    {post_10}
];

Now only if this was in React state this could have been done by using previous states the redux part causes the trouble for me!

If your previous state has a posts key, you can use:

[...state, ...payload]

or maybe

[...state.posts, ...payload]

It can be done in the same way you are passing the payload. You can pass multiple arrays while doing array de-structuring.

case POST_LOAD_SUCCESS:
        return {
            ...state,
            posts: [...state.posts, ...payload]
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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