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

时间:2018-06-18 18:28:09

标签: javascript reactjs react-native

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

我想按其ID过滤searchResults。比较id以返回具有不在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);
            });
        });
    };
}

1 个答案:

答案 0 :(得分:1)

首先应检查项目是否已存在,然后再将其推送到数组。

<强>示例

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