最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactRedux - Add object to start of array using spread operator - Stack Overflow

programmeradmin0浏览0评论

I am using a redux reducer to add objects to a state array. This is working correctly, however, the objects are being added to the end of the array. I have searched high and low, but cannot figure out how to use this syntax, not mutate the array and add the object to the start of an array.

export default (state = [], action) => {

    switch(action.type) {

    case 'MOVIE_ADDED_TO_WATCHLIST':

            return [
                ...state,
                action.movie
            ];

        }

...****rest of the reducer here****.....

I am using a redux reducer to add objects to a state array. This is working correctly, however, the objects are being added to the end of the array. I have searched high and low, but cannot figure out how to use this syntax, not mutate the array and add the object to the start of an array.

export default (state = [], action) => {

    switch(action.type) {

    case 'MOVIE_ADDED_TO_WATCHLIST':

            return [
                ...state,
                action.movie
            ];

        }

...****rest of the reducer here****.....
Share Improve this question asked Feb 10, 2017 at 13:19 peter flanaganpeter flanagan 9,79027 gold badges81 silver badges138 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

If you want to use the spread operator to add items to the beginning of an array, just use the spread operator after the new values. For example:

let a = [1, 2, 3, 4, 5];
let b = [0, ...a];

console.log(a);
console.log(b);

Additionally, you can also use .concat:

var a = [1, 2, 3, 4, 5];
var b = [0].concat(a);

console.log(a);
console.log(b);

You can see a working example of this here.

发布评论

评论列表(0)

  1. 暂无评论