React项目不会从数组中删除

时间:2019-11-10 22:05:45

标签: reactjs redux

我在这里有此代码:

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状态中删除。为什么不删除?

2 个答案:

答案 0 :(得分:2)

看起来您可能需要比较ID以在unlikeMovie函数中过滤出电影。

在不了解movie对象的结构的情况下很难确定,但假设代码示例中的action.movieitem是同一类型的对象,并且它们都共享一个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;