如何检查某个数组是否已包含imdbID并阻止其再次添加?

时间:2018-06-25 21:04:17

标签: javascript reactjs debugging

enter image description here

每部电影只应添加一次到收藏夹列表中,但是此错误使它成为错误,因此每次我更改页面并返回到该特定电影页面并添加它时,它都会将自身推入“收藏夹”数组中。如何检查某个imdbID是否已经存在,并阻止应用将其添加到状态中?

 updateFavorites = movie => {

    if (!this.state.favorites.includes(movie)) {

        const newFavoriteList = this.state.favorites;
        newFavoriteList.push(movie);
        this.setState(state => ({
            favorites: newFavoriteList
        }));


        console.log("Added to your favorites.");

    } else {
        const newFavoriteList = this.state.favorites;
        newFavoriteList.splice(newFavoriteList.indexOf(movie), 1);
        this.setState(state => ({
            favorites: newFavoriteList
        }));
        console.log("Removed from your favorites.");
    }

};

这就是我从收藏夹列表添加和删除电影的方式。

2 个答案:

答案 0 :(得分:0)

如评论中所述,您可以使用.find.findIndex进行比较。另外,您可以使用.filter代替.splice.indexOf来删除电影。我个人更喜欢这种方法。

updateFavorites = ( movie ) => {
    const { favorites } = this.state;
    const checkMovie = favorites.find( fav => fav.imdbID === movie.imdbID );

    if (!checkMovie) {
      return this.setState(
          prevState => ( { favorites: [ ...prevState.favorites, movie ] } ) );
    }

    const newFavoriteList = favorites.filter( fav => fav.imdbID !== movie.imdbID );
    this.setState( { favorites: newFavoriteList } );
  };

答案 1 :(得分:0)

尝试一下,它对我有用

let checkArray = favorites.every( (item) => {
 return item.imdbID !== newItem.imdbID; // newItem is new element for insert
})

if(checkArray) {
  //code for insert newItem
}