这是我的 Sort.js 样式组件:
<SortWrapper> <SortText>Sort By</SortText> <SortSelect onChange={onSelectChange}> <SortOption value="vehicleMake">Vehicle make</SortOption> <SortOption value="vehicleModel">Vehicle model</SortOption> </SortSelect> </SortWrapper>
这是 App.js 中的函数,其中渲染排序组件
<Sort onSelectChange={onSelectChange} />
这是一个函数:
const onSelectChange = (e) => { const value = e.target.value; if (value === "VehicleMake") vehicles.sort((a, b) => a.vehicleMake.localeCompare(b.vehicleMake)); else if (value === "VehicleModel") { vehicles.sort((a, b) => a.vehicleModel.localeCompare(b.vehicleModel)); } else { vehicles.sort((a, b) => a.id - b.id); }
“车辆”是我从 Firestore 数据库获取的对象数组。
每当我更改 SortOption 的值时,它都不会自动对对象数组进行排序,但当我单击分页中的第 2 页,然后单击第 1 页时,它会对其进行排序。
这是我的网格组件:
<Grid> {vehiclesData.map((vehicle) => ( <VehicleCard id={vehicle.id} key={vehicle.id} ImageURL={vehicle.ImageURL} vehicleMake={vehicle.vehicleMake} vehicleModel={vehicle.vehicleModel} selectVehicle={() => setSelectedVehicle(vehicle)} deleteHandler={() => deleteHandler(vehicle.id)} /> ))} </Grid>
这是我的过滤功能:
const vehiclesData = useMemo(() => { let computedVehicles = vehicles; if (searchVehicle) { computedVehicles = computedVehicles.filter((vehicle) => vehicle.vehicleMake.toLowerCase().includes(searchVehicle.toLowerCase()) ); } setTotalVehicles(computedVehicles.length); return computedVehicles.slice( (currentPage - 1) * vehiclesPerPage, (currentPage - 1) * vehiclesPerPage + vehiclesPerPage );
正如我之前所写,我希望我的车辆按品牌或型号自动渲染,而不是在我单击分页中的页码时渲染。
P粉7908197272024-04-07 15:43:05
你的排序方法应该是这样的
const onSelectChange = (e) => { let temVehicles = [...vehicles] const value = e.target.value; if (value === "VehicleMake") temVehicles .sort((a, b) => a.vehicleMake.localeCompare(b.vehicleMake)); else if (value === "VehicleModel") { temVehicles .sort((a, b) => a.vehicleModel.localeCompare(b.vehicleModel)); } else { temVehicles .sort((a, b) => a.id - b.id); } setVehicles(temVehicles )}
你的过滤函数应该是这样的
const vehiclesData = useMemo(() => { let computedVehicles = vehicles; if (searchVehicle) { computedVehicles = computedVehicles.filter((vehicle) => vehicle.vehicleMake.toLowerCase().includes(searchVehicle.toLowerCase()) ); } setTotalVehicles(computedVehicles.length); return computedVehicles.slice( (currentPage - 1) * vehiclesPerPage, (currentPage - 1) * vehiclesPerPage + vehiclesPerPage );},[vehicles])
基本上,一旦 onSelectChange 运行,您就会更新车辆状态,然后 usememo 应该再次运行,因此我们向其中添加依赖车辆