我在这里有此代码:
const favouriteMovies = (state = initialState, action) => {
switch(action.type) {
case 'setMovieToFavourites': return {
...state,
hearted: [...state.hearted, action.movie]
}
default: return state;
}
}
const unlikeMovie = (state = initialState, action) => {
switch(action.type) {
case 'unlikeMovie': return {
...state,
hearted: state.hearted.filter(item => item !== action.movie),
}
default: return state;
}
}
因此,第一个功能favouriteMovies
将影片添加到数组中,而第二个功能我想从hearted
影片中删除该影片。在unlikeMovie
函数中,我获得了与liked
电影之一相等的movieID,但它不会将电影从hearted
状态中删除。为什么不删除?
答案 0 :(得分:2)
看起来您可能需要比较ID以在unlikeMovie
函数中过滤出电影。
在不了解movie
对象的结构的情况下很难确定,但假设代码示例中的action.movie
与item
是同一类型的对象,并且它们都共享一个movieID
的ID属性,应该可以这样工作:
const unlikeMovie = (state = initialState, action) => {
switch(action.type) {
case 'unlikeMovie': return {
...state,
hearted: state.hearted.filter(item => item.movieID !== action.movie.movieID),
}
default: return state;
}
}
希望这会有所帮助!
答案 1 :(得分:1)
您可以检查此代码吗?
const movies = (state = initialState, action) => {
switch(action.type) {
case 'setMovieToFavourites': return {
...state,
hearted: [...state.hearted, action.movie]
}
case 'unlikeMovie': return {
...state,
hearted: state.hearted.filter(item => item !== action.movie),
}
default: return state;
}
}
export default movies;