简体   繁体   English

使用 splice() 删除项目

[英]delete item with splice()

I display in a component some movies that I get with an API call and a .map method.我在一个组件中显示了一些通过 API 调用和.map方法获得的电影。 When I try to delete an item into this list of movies, the deletion is only done on the last item.当我尝试将一个项目删除到此电影列表中时,仅对最后一个项目进行删除。 I use the splice() method and I give an index to my deleteMovieFromFav() function.我使用splice()方法并为deleteMovieFromFav() function 提供索引。 I don't know what I'm missing.. Would anyone know how to do it?我不知道我错过了什么..有人知道该怎么做吗?

the function for delete a movie: function 用于删除电影:

deleteMovieFromFav = (idx) => {
    let { movies } = this.props.movieReducer;
    movies.splice(idx, 1)
    this.setState({movies: [...movies]})
}

onClick for delete a movie: onClick用于删除电影:

{
 this.props.movieReducer.movies.map((movie, idx) => {
  return(
   <div key={idx}>
    <Snackbar
      action={[
       <Button key="undo" color="secondary" size="small" 
        onClick={() => {
         this.deleteMovieFromFav(idx)
         this.handleCloseAlert()
        }}> Yes
       </Button>,
       <Button 
        key="no" 
        color="secondary" 
        size="small" 
        onClick={() => this.handleCloseAlert()}>
      ]}
    />
  </div>
 )
})
}

I used redux and I created an action for delete a movie from favorites, and now it is the first element that is deleted.. I would like my deleteMovie action to act on the id of the movie that has been added as favorites but I have access to this id only in the .map and not in redux..我使用了 redux 并创建了一个从收藏夹中删除电影的动作,现在它是第一个被删除的元素。只能在.map中访问此 ID,而不能在 redux 中访问。

movieReducer here: movieReducer在这里:

import { DELETE_MOVIE } from '../actionType/movies'

const initialState = {
  movies: []
};

export default (state = initialState, action) => {
  switch(action.type){
    case DELETE_MOVIE: 
      let selectedMovies = state.movies
      selectedMovies.splice(action.payload, 1)
      return {...state, movies: [...selectedMovies]};
    default:
      return state;
  }
}

movieActions here: movieActions在这里:

import { ADD_MOVIE, DELETE_MOVIE } from '../actionType/movies'
export const deleteMovie = (movie) => {
  console.log('movieid', movie)
  return {
    type: DELETE_MOVIE,
    payload: movie
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM