React Router DOM:如何通过单URL参数实现商品分类筛选
解决方案
核心思路
通过前端维护(或从后端拉取)一份分类与子分类的映射关系表,根据路由参数的value判断它是父分类还是子分类,若为子分类则自动匹配对应的父分类slug,再构造正确的查询参数发送请求。
具体实现步骤
构建分类映射表
先从后端获取全部分类数据(可在应用初始化时请求一次并缓存),将其转换为以slug为键的对象,存储每个slug对应的父分类slug:// 假设从后端接口获取的全部分类数据为categories数组 const buildCategoryMap = (categories) => { const categoryMap = {}; categories.forEach(category => { // 父分类的父slug设为null categoryMap[category.slug] = { parentSlug: null }; // 遍历子分类,关联对应的父分类slug category.sub_category.forEach(subCat => { const parentCategory = categories.find(cat => cat.id === subCat.parent); categoryMap[subCat.slug] = { parentSlug: parentCategory?.slug || null }; }); }); return categoryMap; }; // 示例:初始化时获取并缓存映射表 let categoryMap = {}; fetch('/api/categories') .then(res => res.json()) .then(categories => { categoryMap = buildCategoryMap(categories); });在ShopProducts组件中处理路由参数
使用路由钩子获取value参数,通过映射表判断类型,生成正确的查询参数:import { useParams } from 'react-router-dom'; function ShopProducts() { const { value } = useParams(); let category = ''; let subCategory = ''; // 从映射表中查找当前slug的信息 const slugInfo = categoryMap[value]; if (slugInfo) { if (slugInfo.parentSlug === null) { // 当前是父分类 category = value; } else { // 当前是子分类,关联对应的父分类 category = slugInfo.parentSlug; subCategory = value; } } // 构造查询字符串 const queryParams = new URLSearchParams(); if (category) queryParams.append('category', category); if (subCategory) queryParams.append('sub-category', subCategory); // 发送筛选请求 fetch(`/api/products?${queryParams.toString()}`) .then(res => res.json()) .then(productData => { // 处理商品数据渲染 }); // 组件渲染逻辑... }路由配置保持单参数结构
保持你想要的路由配置不变:<Route path={process.env.PUBLIC_URL + "/:value"} component={ShopProducts} />
优势说明
- 直接访问URL时,组件挂载会自动执行参数判断逻辑,无需依赖前端状态(比如Redux),解决了直接访问失效的问题。
- 映射表可以通过后端接口动态更新,扩展性强,新增分类/子分类时只需同步后端数据即可。
内容的提问来源于stack exchange,提问作者tav
相关产品推荐
相关产品推荐

