创建一个数组.map中的push正在覆盖之前的数据(reactJs)



我有一个数组(A),它返回我在Api调用的params函数中使用的许多项,所以我用这个数组制作了一个映射,对于每个项,我进行Api调用并使用。然后,使用数据响应想要创建一个新的数组(B)。

问题:数组B由相同数量的项组成,但这些项是重复的,而不是唯一的项。

我的代码:

useEffect(() => {
// the Array A in the question / // 
moviesId.arr.map((item) => {
// the Api Call function in the question /  //    

ApiMovieList(item).then((data) => {
let a = [];
for (var x = 0; x < moviesId.arr.length; x++) {
a.push(data.poster_path);
}
// the Array B in the question / //  
var UserDataEntry = a || [];

console.log(UserDataEntry);


});
});
});

控制台显示:

(2) ["Matrix", "Matrix"] 

Instead of this:
(2) ["Ghost", "Matrix"]

请问如何解决这个问题?

我的数据:

moviesId.arr = ["451048", "436969"]

ApiMovieList(项),然后((数据)=比;data = string("Matrix", "Ghost")例如,它取决于moviesId.arr

的位置。

您不应该使用.map的副作用。你正在迭代moviesId.arr数组和然后表示将data.poster_path值的moviesId.arr.length个数压入a数组的每个元素。这就是你的副本的来源。

我建议在promise数组中加载ApiMovieList(item)调用,并使用Promise.all等待所有这些调用都解决。然后,您将有一个已解析的海报路径数组,可将其设置为UserDataEntry和log。

useEffect(() => {
// the Array A in the question
const posterReqs = moviesId.arr.map(item => {
return ApiMovieList(item).then(data => data.poster_path);
});
Promise.all(posterReqs).then(posters => {
// the Array B in the question
const UserDataEntry = posters || []; 
console.log(UserDataEntry);
});
});

最新更新