使用排列运算符有条件地添加到对象数组中



如果数组符合特定条件(即,如果电影id与我的数组中已经存在的其他电影id不匹配(,我想使用排列运算符有条件地向数组中添加一些内容

case ADD_FAVORITE:
return {
...state,
favorites: [ state.favorites !== action.payload.id? ...state.favorites, action.payload]
}

这就是我尝试过的

行动有效载荷返回类似的东西

{id: 0, title: 'The Godfather', director: 'Francis Ford Coppola', metascore: 100, genre: 'Drama', …}

和内部状态。避免:

description: "Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a Wookiee and two droids to save the galaxy from the Empire's world-destroying battle station, while also attempting to rescue Princess Leia from the mysterious Darth Vader."
director: "George Lucas"
genre: "Scifi"
id: 1
metascore: 92
title: "Star Wars"
[[Prototype]]: Object

我会在return之前进行检查,因为如果没有任何变化,您根本不需要更新state

case ADD_FAVORITE:
if (state.favorites.some(({id}) => id === action.payload.id)) {
// It's already there, we don't need to modify state at all
return state;
}
return {...state, favorites: [...state.favorites, action.payload]};

如果想要更新状态,即使没有任何更改,只需在分支中执行即可:

case ADD_FAVORITE:
if (state.favorites.some(({id}) => id === action.payload.id)) {
// It's already there, we don't need to modify state at all
return {...state};
}
return {...state, favorites: [...state.favorites, action.payload]};

case ADD_FAVORITE:
let favorites = state.favorites;
if (!favorites.some(({id}) => id === action.payload.id)) {
// Don't have it, add it
favorites = [...favorites, action.payload];
}
return {...state, favorites};

(同样,如果您想返回一个新的状态对象,即使没有任何变化。(

最新更新