如何基于Redux Toolkit的productSlice实现产品分类筛选功能
分类过滤逻辑实现方案
1. 补全 productSlice 内的 reducer 逻辑
首先修正初始状态里的适配问题:原categories数组里的&是Web端的HTML转义字符,React Native环境下不需要这类转义,建议直接替换为带&的正常字符串(比如'Engine & Emissions'),避免和产品对象里的category字段匹配失败。
你原本在分类标签组件里写的onPress={() => dispatch(filterList(index))}逻辑不需要改动,传入的分类索引刚好是reducer需要的入参,具体实现如下:
分类过滤 filterList
按照传入的分类索引更新状态:
- 同步更新
selectedCategory为当前点击的分类索引 - 当索引为0(对应分类
All)时,重置筛选标记、清空过滤结果,回到展示全量产品的状态 - 当索引为其他分类时,从全量产品列表里筛选出
category和选中分类名一致的条目,存入filteredList,同时标记hasAppliedFilter为已应用筛选
对应代码:
filterList: (state, action) => { const selectedIndex = action.payload; // 更新选中分类的索引 state.selectedCategory = selectedIndex; // 选中"All"的情况 if (selectedIndex === 0) { state.hasAppliedFilter = false; state.filteredList = []; return; } // 按选中分类名过滤全量产品 const selectedCategoryName = state.categories[selectedIndex]; state.filteredList = state.products.filter( product => product.category === selectedCategoryName ); state.hasAppliedFilter = true; }
搜索逻辑 searchList
兼容分类筛选的状态,避免搜索覆盖之前的分类筛选结果:
- 以用户输入的关键词为基准,优先在已筛选的列表范围内搜索,没有应用分类筛选时就从全量产品里搜索
- 搜索匹配产品名称、描述字段包含关键词的条目,存入
searchResult - 当用户清空搜索框时,直接清空搜索结果,回到分类筛选/全量展示的状态
对应代码:
searchList: (state, action) => { const inputKeyword = action.payload.trim().toLowerCase(); // 输入为空时清空搜索结果 if (!inputKeyword) { state.searchResult = []; return; } // 确定搜索的基准范围:有分类筛选就从筛选结果里搜,否则从全量产品搜 const baseList = state.hasAppliedFilter ? state.filteredList : state.products; state.searchResult = baseList.filter(product => product.name.toLowerCase().includes(inputKeyword) || product.desc.toLowerCase().includes(inputKeyword) ); }
2. ProductSection 列表渲染适配
渲染产品列表时按照优先级判断要展示的数据源:
- 若
searchResult非空,优先展示搜索结果 - 若
hasAppliedFilter为true,展示分类过滤后的filteredList - 其余情况展示全量的
products数组
这样可以同时兼容三种状态:未筛选的全量产品、按分类筛选的产品、带搜索关键词的筛选结果,不会出现状态冲突。
内容的提问来源于stack exchange,提问作者B_M
相关产品推荐
相关产品推荐

