Javascript 如何筛选出以前未添加到React Native中数组的项?

Javascript 如何筛选出以前未添加到React Native中数组的项?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,每当用户在我们的应用程序中进行产品搜索时,我们都需要将搜索结果缓存在本地存储中,以便当他们脱机时,执行搜索时,它可以调出以前搜索过的项目。对于每个新搜索,我们只需要将新项目添加到searchCache。因此,如果他们先搜索“be”,然后再搜索“b”,则会有重叠的结果,但我们不希望添加已存储的项目。但这目前不起作用,因为它仍然返回搜索中的所有项目,而不是过滤它们。有人知道如何做到这一点吗 我想根据他们的ID过滤搜索结果。比较ID以返回ID不在searchCache中的项目 newItems = s

每当用户在我们的应用程序中进行产品搜索时,我们都需要将搜索结果缓存在本地存储中,以便当他们脱机时,执行搜索时,它可以调出以前搜索过的项目。对于每个新搜索,我们只需要将新项目添加到searchCache。因此,如果他们先搜索“be”,然后再搜索“b”,则会有重叠的结果,但我们不希望添加已存储的项目。但这目前不起作用,因为它仍然返回搜索中的所有项目,而不是过滤它们。有人知道如何做到这一点吗

我想根据他们的ID过滤搜索结果。比较ID以返回ID不在searchCache中的项目

newItems = searchResults.filter((searchResult) => {
    return searchCache.find(searchCacheItem => searchCacheItem.id !== searchResult.id);
});
以下是整个动作功能:

export function handleProductSearch(searchTerm) {
    return (dispatch, getState) => {
        return dispatch(getProductList(searchTerm)).then((results) => {
            const searchResults = results.items;

            // Get previously stored product search cache
            AsyncStorage.getItem(STORAGE_KEY_PRODUCT_SEARCH_CACHE).then((results) => {
                return JSON.parse(results);
            }).then((response) => {
                const searchCache = response || [];
                let newItems = [];

                if (searchCache.length > 0) {
                    // Check for duplicates in the recently added items.  Only add the items that are new and not already in the searchCache.
                    newItems = searchResults.filter((searchResult) => {
                        return searchCache.find(searchCacheItem => searchCacheItem.id !== searchResult.id);
                    });
                }

                searchCache.push(newItems.length > 0 ? newItems : searchResults);
                AsyncStorage.setItem(STORAGE_KEY_PRODUCT_SEARCH_CACHE, JSON.stringify(searchCache));
            }).catch(err => {
                console.log('Error retrieving product search cache: ', err);
            });
        });
    };
}

您应该首先检查该项是否已经存在,如果不存在,则将其推送到数组中

样本

let newItems = [];

if (searchCache.length > 0) {
  // Check for duplicates in the recently added items.  Only add the items that are new and not already in the searchCache.
  searchResults.forEach(searchResultItem => {
    if(!searchCache.find(searchCacheItem => searchCacheItem.id === searchResultItem.id)) newItems.push(item)
  });
}

我想您应该执行
searchCacheItem.id==searchResultItem.id
并检查falsy?@RaphaMex是否正确谢谢您的修复。我已经更新了答案。为什么您只想推送新结果?是否有大量的旧结果,或者您修改了一些结果以便保留它们?就像现在一样,只需重建searchCache就可以更加高效。。。