You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js价格排序功能异常:SELECT组件无法实现价格升降序

解决React中价格排序SELECT组件失效问题

核心问题排查

  • 值匹配错误:SELECT中「High Price」选项的value是"high-price",但判断条件写的是value === "highest price",完全不匹配,导致高价排序逻辑根本不会触发。
  • 原数组被修改:Array.sort()是原地排序,直接调用products.sort()会修改原始的products数组,导致后续状态混乱。
  • 搜索逻辑依赖错误:searchProducts里用productsInfo来过滤,而非原始products,会导致多次搜索后数据被截断,无法回到完整列表。

修复后的代码

1. 修正排序事件处理函数

const selectedChangeFilter = (e) => {
  const { value } = e.target;
  // 先复制原始数组,避免修改原数据
  let sortedProducts = [...products];

  if (value === "low-price") {
    sortedProducts.sort((el1, el2) => 
      el1.price.localeCompare(el2.price, undefined, { numeric: true })
    );
  } else if (value === "high-price") { // 修正值匹配
    sortedProducts.sort((el1, el2) => 
      el2.price.localeCompare(el1.price, undefined, { numeric: true })
    );
  } else { // value === "all"
    sortedProducts = [...products]; // 重置为原始数组
  }
  setProductsInfo(sortedProducts);
};

2. 修复搜索函数

const searchProducts = () => {
  const trimmedValue = searchValue.toLowerCase().trim();
  if (trimmedValue === "") {
    setProductsInfo([...products]); // 重置为原始数据
  } else {
    // 基于原始products过滤,而非productsInfo
    const seekedItem = products.filter(
      (product) =>
        product.name.toLowerCase().trim().includes(trimmedValue) ||
        product.category.toLowerCase().trim().includes(trimmedValue)
    );
    setProductsInfo(seekedItem);
  }
};

3. 确保分页逻辑依赖productsInfo

你的displayPage需要基于productsInfo计算分页,示例逻辑如下:

const itemsPerPage = 8;
const displayPage = productsInfo.slice(
  pageNumber * itemsPerPage,
  (pageNumber + 1) * itemsPerPage
);

额外注意事项

  • 始终避免直接修改React状态或原始数据源,操作前先通过[...products]或products.slice()做数组拷贝。
  • 条件判断优先用else if,避免多个独立if导致逻辑冲突。
  • 确保products是原始完整商品列表,仅通过productsInfo维护过滤/排序后的状态。

内容的提问来源于stack exchange,提问作者user296308

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:45:40