javascript API调用中的重复对象

cvxl0en2  于 2022-10-30  发布在  Java
关注(0)|答案(1)|浏览(104)

我尝试使用无限滚动通过这样做:

但是,当我将数据传递给sticks状态,然后进行Map时,调用的第一个项目被复制了。例如:

请注意,gif文件是重复的。但是,无限滚动是正确的工作。当它运行时,它会用新的gif文件进行新的调用,并将它们添加到屏幕上,而不重复它们。只有这些早期状态的第一个开始重复。代码如下所示:

有人知道我怎么解决这个问题吗?

bmvo0sr5

bmvo0sr51#

看起来每个gif都有一个id,所以你只需要一种方法来filter出所有那些id在当前项数组中不存在的新项。

// Accept the current array of gifs, and a new array of gifs
function dedupeGifs(gifs, newGifs) {

  // `map` over the current array of gifs
  // to create an array of ids
  const gifsIds = gifs.map(gif => gif.id);

  // `filter` out all those gifs that don't
  // already exist
  return newGifs.filter(gif => {
    return !gifsIds.includes(gif.id);
  });
}

然后将当前阵列与已消除重复数据的阵列合并在一起:

const dedupedItems = dedupeGifs(gifs, newGifs);
setState(prev, [ ...prev, ...dedupedGifs ]);

相关问题