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

React.js实现商品列表按价格及字母序排序的代码实现问题咨询

Hey there! Let's walk through how to add that sorting functionality step by step—you were right about needing state, so let's build out the rest:

1. Set Up State and Basic Imports

First, we'll add state to track the selected sorting option, and make sure we have the tools we need from React:

import { useState } from 'react';

// Replace this with your actual full product dataset
const allProducts = [
  { id: 1, name: "Wireless Headphones", price: 199 },
  { id: 2, name: "Phone Case", price: 29 },
  { id: 3, name: "Bluetooth Speaker", price: 89 },
  // ... more products
];

function ProductList() {
  // Track the active sorting option
  const [sortOption, setSortOption] = useState('default');
  // Pagination state (if you're using it—adjust values to match your setup)
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 4;

2. Add Sorting Logic

Next, we'll create a sorted version of our product array based on the selected option:

// Create a sorted copy of the product array
  const sortedProducts = [...allProducts].sort((a, b) => {
    switch (sortOption) {
      case 'ascending':
        // Sort by product name A-Z (supports multi-language sorting)
        return a.name.localeCompare(b.name);
      case 'descending':
        // Sort by product name Z-A
        return b.name.localeCompare(a.name);
      case 'high-price':
        // Sort by price from highest to lowest (ensure price is a number!)
        return b.price - a.price;
      case 'low-price':
        // Sort by price from lowest to highest
        return a.price - b.price;
      default:
        // Default sort (keep original order, using ID as a fallback)
        return a.id - b.id;
    }
  });

3. Integrate Pagination (If Needed)

If your displayPage is for pagination, apply it after sorting to ensure you're paginating the sorted results:

// Calculate which items to show on the current page
  const startIndex = (currentPage - 1) * itemsPerPage;
  const displayPage = sortedProducts.slice(startIndex, startIndex + itemsPerPage);

4. Update the Select Dropdown

Wire up the dropdown to update our sorting state when the user selects an option:

return (
    <>
      <Col lg="6" md="6" sm="6" xs="12" className="mb-5">
        <div className="sorting__widget text-end">
          <select 
            className="w-50" 
            value={sortOption}
            onChange={(e) => setSortOption(e.target.value)}
          >
            <option value="default">默认排序</option>
            <option value="ascending">字母顺序,A-Z</option>
            <option value="descending">字母顺序,Z-A</option>
            <option value="high-price">价格从高到低</option>
            <option value="low-price">价格从低到高</option>
          </select>
        </div>
      </Col>
      {displayPage.map((item) => (
        <Col lg="3" md="4" sm="6" xs="6" key={item.id} className="mb-4">
          <ProductCard item={item} />
        </Col>
      ))}
    </>
  );
}

export default ProductList;

Quick Notes to Adjust for Your Project

  • Field Names: Make sure name and price match the actual keys in your product objects (e.g., if your product name is stored as title, replace a.name with a.title).
  • Price Formatting: If your prices are strings (like "$199"), convert them to numbers first: parseFloat(a.price.replace(/[^0-9.]/g, '')).
  • Pagination Libraries: If you're using a pagination library instead of manual slicing, pass the sortedProducts array as the data source to the library.

内容的提问来源于stack exchange,提问作者Ricardo Sánchez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:37:27