React+Redux餐厅桌位多条件叠加筛选功能失效问题咨询
问题根因
你当前的筛选逻辑存在两个核心问题导致条件无法叠加:
- 组件没有存储已选的位置、容量两个筛选值,每次触发任意筛选操作,都只拿当前修改的单个条件去过滤全量桌位原始数据,直接覆盖了上一次的筛选结果
- 两个筛选的处理函数完全独立,没有互相引用对方的筛选条件做叠加校验
修改方案
我们可以直接在筛选组件内用state存储两个当前生效的筛选值,任意值变化时统一用两个条件叠加过滤全量数据即可,修改后的TableFilter.tsx代码如下:
import { Form } from 'react-bootstrap'; import { useSelector, useDispatch } from 'react-redux'; import { useState, useEffect } from 'react'; import { filterTables } from '../../store/actions'; import { tableI } from '../../Interfaces'; const TableFilter: React.FC = () => { const tables: tableI[] = useSelector((state: any) => state.tables.tables); const dispatch = useDispatch(); // 存储当前选中的两个筛选条件 const [selectedLocation, setSelectedLocation] = useState<string>(''); const [selectedCapacity, setSelectedCapacity] = useState<number>(0); // 统一的叠加筛选逻辑 const applyCombinedFilters = () => { let filteredTables = [...tables]; // 叠加位置筛选:有选中值才生效 if (selectedLocation) { filteredTables = filteredTables.filter(table => table.location === selectedLocation); } // 叠加容量筛选:有选中值才生效 if (selectedCapacity > 0) { filteredTables = filteredTables.filter(table => table.capacity >= selectedCapacity); } dispatch(filterTables(filteredTables)); }; // 位置筛选变更处理 const handleLocationChange = (event: any) => { const value = event.target.value; // 选择默认提示项时清空筛选条件 setSelectedLocation(value === 'Select your table\'s location' ? '' : value); }; // 容量筛选变更处理 const handleCapacityChange = (event: any) => { const value = event.target.value; // 选择默认提示项时清空筛选条件 setSelectedCapacity(value === 'Number of persons sitting ' ? 0 : Number.parseInt(value)); }; // 任意筛选条件变化时重新执行叠加筛选 useEffect(() => { applyCombinedFilters(); }, [selectedLocation, selectedCapacity]); const locations: string[] = tables.map((table) => table.location); const capacity: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const uniqueLocations = [...new Set(locations)]; return ( <Form> <Form.Group className="mb-3" controlId="formBasicLocation"> <Form.Label>Select a table</Form.Label> <Form.Control onChange={handleLocationChange} as="select" aria-label="form-select-location" > <option>Select your table's location</option> {uniqueLocations && uniqueLocations.map((location: string, index: number) => ( <option aria-label="location" key={index} value={location}> {location} </option> ))} </Form.Control> </Form.Group> <Form.Group className="mb-3" controlId="formBasicCapacity"> <Form.Label>Select the capacity of your table</Form.Label> <Form.Control onChange={handleCapacityChange} as="select" aria-label="form-select-capacity" > <option>Number of persons sitting </option> {capacity && capacity.map((cap: number, index: number) => ( <option aria-label="capacity" key={index} value={cap}> {cap} </option> ))} </Form.Control> </Form.Group> </Form> ); }; export default TableFilter;
可选优化
如果你需要筛选条件在页面刷新、组件卸载后仍保留,可以将selectedLocation和selectedCapacity两个状态存入Redux中,新增对应的action和reducer处理逻辑即可,筛选逻辑不需要做额外调整。
内容的提问来源于stack exchange,提问作者Michelangelo
相关产品推荐
相关产品推荐

