搜尋

首頁  >  問答  >  主體

如何在 React 中的排序方法上觸發渲染(帶有過濾器和分頁)?

這是我的 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粉970736384P粉970736384248 天前2465

全部回覆(1)我來回復

  • P粉790819727

    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 應該再次運行,因此我們向其中添加依賴車輛

    回覆
    0
  • 取消回覆