React/Redux - 使用spread运算符添加对象以启动数组

pet*_*gan 4 javascript arrays reactjs redux

我使用redux reducer将对象添加到状态数组.这是正常的,但是,对象被添加到数组的末尾.我已经搜索了高低,但无法弄清楚如何使用这种语法,而不是改变数组并将对象添加到数组的开头.

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

    switch(action.type) {

    case 'MOVIE_ADDED_TO_WATCHLIST':

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

        }

...****rest of the reducer here****.....
Run Code Online (Sandbox Code Playgroud)

Jac*_*och 9

如果要使用spread运算符将项添加到数组的开头,只需在新值之后使用spread运算符.例如:

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

console.log(a);
console.log(b);
Run Code Online (Sandbox Code Playgroud)

此外,您还可以使用.concat:

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

console.log(a);
console.log(b);
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到一个有效的例子.