In a function associated with an API call: Uncaught (in promise) TypeError: Cannot read property 'includes' of undefined

In a function associated with an API call: Uncaught (in promise) TypeError: Cannot read property 'includes' of undefined

我正在使用电影数据库 API(https://developers.themoviedb.org/3/genres/get-movie-list 这个) 然后我用 VUE 在我的页面上打印我的调用结果。 API 为我提供了实现目标所需的所有数据,就是这个

如您所见,在节目名称下有与该名称关联的流派。 让我们以 API 给我 A-Team

时我获得的对象为例
"backdrop_path": "/ggPjnOA5sap6wyuAGUY7kwRseEi.jpg",
            "first_air_date": "1983-01-23",
            "genre_ids": [
                10759
            ],
            "id": 1516,
            "media_type": "tv",
            "name": "A-Team",
            "origin_country": [
                "US"
            ],
            "original_language": "en",
            "original_name": "The A-Team",
            "overview": "Un commando di ex-combattenti della guerra del Vietnam chiamato A-Team (Squadra A), un tempo appartenenti ai corpi speciali dell'esercito degli Stati Uniti, viene accusato ingiustamente di aver rapinato la banca di Hanoi. Evasi in maniera rocambolesca, vivono ora in fuga, ricercati e braccati dalle autorità per un reato che non hanno mai commesso. I componenti della squadra sopravvivono prestando servizio come mercenari e venendo, nella quasi totalità degli episodi, assoldati da varie persone o gruppi di persone che vivono oppresse da situazioni d'ingiustizia nei propri confronti. Grazie alle qualità militari e umane dell'A-Team, ogni episodio si risolve in maniera definitiva a favore dei più deboli. Pur essendo visti come mercenari dagli altri personaggi della serie, i membri dell'A-Team sono dunque schierati sempre dalla parte del bene. Famoso è il loro furgone GMC Vandura nero e grigio con 2 strisce rosse laterali che si uniscono sullo spoiler superiore, usato come mezzo principale di trasporto dell'A-Team.",
            "popularity": 141.786,
            "poster_path": "/iJsueZM8TqQzeB55tol4mnyQzb9.jpg",
            "vote_average": 7.4,
            "vote_count": 574
        },

如您所见,有一个名为 genre_ids 的子数组,其中包含此特定节目的相关类型的 ID。为了获得名称,我使用了另一个 API 调用,它为我提供了一个对象数组,其中每个对象都有两个属性,一个流派的 id 和一个流派的名称。因此,从这个数组中,您可以轻松获取节目的相关流派名称并打印出来。 我是这样操作的,在shows'API调用得到的数组上做.map

searchShow()是上图中input中回车启动的函数,this.userSearch其实就是关联的v-model input.

searchShow() {
            axios
                // this is the call that provides me an array of object like the A-Team's one seen before
                .get(`https://api.themoviedb.org/3/search/multi`, {
                params: {
                            api_key: this.apiKey,
                            query: this.userSearch,
                            language: this.userLanguage,
                        },
                })
                .then((response) => {
                    const result = response.data.results;
                    // I save result in an empty array created in data 
                    this.searchResults = result;

                    // I insert a new property inside the array obtained right now,
                    // this property provides me genres name
                    
                    const newArray = this.searchResults.map ((element) => {
                        let objectResults = element.genre_ids;
                        let object = element;
                        // object.genres_name it's an empty array where I save in my results
                        object.genres_name = [];
                        // this.genresList it's the array in which I've saved the API call that gives me objects with ids and genres's name
                            this.genresList.forEach(genre => {
                            // ids of genres are the same everywhere. If the ones in the 
                            // genresList array are included in each element.genre_ids
                            // then push the name as an object, so it's printable in HTML
                            if (objectResults.includes(genre.id)) {
                                object.genres_name.push(
                                    {
                                        genre: genre.name
                                    
                                    }    
                                    );
                                }
                            })
                            
                    // return the element updated
                    return object;
                    })
                    // this.arrayProva is now equal to the map of the original array and it's
                    // the array printed in HTML
                    this.arrayProva = newArray;
                });
        },

有了这个,我可以轻松地在 HTML 中打印流派的名称,因为我在现有流派的基础上添加了一个新的 属性。当一个节目没有关联任何流派时,问题就来了,也许是一个不太出名的节目,但它打破了我的项目,因为错误出现并且 vue 不再打印搜索结果。 发生这种情况是因为单个元素没有我用来将流派名称添加到任何单个节目的子数组流派 ID。 我怎样才能避免这种情况?

如果问题是您只需要处理 API 结果中未定义 element.genre_ids 的情况,我认为您可以简单地更改 objectResults 的赋值成为:

let objectResults = element.genre_ids || [];

如果从 API 获得的数组为空或未定义,这将提供一个默认的空数组。