javascript - 如何在 React Native 中过滤掉之前未添加到数组中的项目?

标签 javascript reactjs react-native

每当用户在我们的应用中进行产品搜索时,我们都需要将搜索结果缓存在本地存储中,以便当他们离线并执行搜索时,它可以提取以前搜索过的项目。对于每个新搜索,我们只需将新项目添加到 searchCache 中。因此,如果他们先搜索“be”,然后搜索“b”,则会出现重叠的结果,但我们不想添加已存储的项目。但这目前不起作用,因为它仍然返回搜索中的所有项目而不是过滤它们。有谁知道如何实现这一目标?

我想按 id 过滤搜索结果。比较 ids 以返回具有不在 searchCache 中的 id 的项目。

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)
  });
}

关于javascript - 如何在 React Native 中过滤掉之前未添加到数组中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50915447/

相关文章:

javascript - 在 javascript 中将 url 作为参数传递时出错

php - 如何使用 JavaScript 检测屏幕 DPI

reactjs - 在 Jenkins 构建中实现 Jest 测试的正确方法

javascript - 正确使用 onCompleted 进行 GraphQL 突变

IOS构建警告: the transform cache was reset

reactjs - 在 React Native 中订阅监听器的通用解决方案

javascript - 仅选择添加到 DOM 的单击元素

javascript - 关于 javascript document.forms[]

javascript - React - setState 不更新数组

Firebase 限制每个查询一个 "array-contains-any"- 如果我需要多个怎么办?