商品列表

按关键词搜索商品、按分类筛选、排序,并以每页 6 件分页显示。

商品列表

要点

  1. 1

    不改动原始数据,只生成要显示的部分

    从全部商品出发,依次经过 filter(筛选)→ sort(排序)→ slice(分页),生成要显示在页面上的部分。原始列表保持不变。

  2. 2

    条件一变,就回到第 1 页

    如果在看第 2 页时搜索,结果可能只有 1 页,页面就变成空的了。只要条件改变,就把页码重置为 1。

  3. 3

    准备好“没有结果”时的显示

    0 件时显示“没有符合条件的商品”,并提供清除条件的按钮。什么都不显示的话,看起来就像坏掉了。

使用的工具

点击查看第 2 部分的比较

修改代码

修改代码,右边的预览会跟着变化。

import { useState } from "react"
import { SearchIcon } from "lucide-react"
import { Button } from "./components/ui/button"
import { Input } from "./components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./components/ui/select"

type Product = {
  id: number
  name: string
  category: string
  price: number
  rating: number
  color: string // 用颜色代替商品图片
}

// 商品数据(12件)
const products: Product[] = [
  { id: 1, name: "无线耳机", category: "数码家电", price: 595, rating: 4.5, color: "#0ea5e9" },
  { id: 2, name: "不锈钢保温杯", category: "厨房", price: 140, rating: 4.2, color: "#10b981" },
  { id: 3, name: "双肩包 20L", category: "服饰", price: 350, rating: 4.7, color: "#f59e0b" },
  { id: 4, name: "台灯", category: "数码家电", price: 280, rating: 4.0, color: "#8b5cf6" },
  { id: 5, name: "咖啡磨豆机", category: "厨房", price: 210, rating: 4.6, color: "#ef4444" },
  { id: 6, name: "运动鞋", category: "服饰", price: 455, rating: 4.3, color: "#ec4899" },
  { id: 7, name: "充电宝", category: "数码家电", price: 182, rating: 4.4, color: "#14b8a6" },
  { id: 8, name: "平底锅 26cm", category: "厨房", price: 161, rating: 4.1, color: "#f97316" },
  { id: 9, name: "棒球帽", category: "服饰", price: 112, rating: 3.9, color: "#6366f1" },
  { id: 10, name: "电热水壶", category: "数码家电", price: 231, rating: 4.5, color: "#84cc16" },
  { id: 11, name: "砧板", category: "厨房", price: 91, rating: 4.0, color: "#a855f7" },
  { id: 12, name: "手表", category: "服饰", price: 735, rating: 4.8, color: "#64748b" },
]

const categories = ["全部", "数码家电", "厨房", "服饰"]

// 每页显示的数量
const pageSize = 6

// 一个商品的卡片
function ProductCard({ product }: { product: Product }) {
  return (
    <div className="overflow-hidden rounded-lg border bg-card">
      <div className="h-24" style={{ backgroundColor: product.color }} />
      <div className="p-3">
        <p className="text-xs text-muted-foreground">{product.category}</p>
        <p className="mt-0.5 text-sm font-medium">{product.name}</p>
        <div className="mt-2 flex items-center justify-between">
          <p className="text-sm font-semibold">¥{product.price.toLocaleString()}</p>
          <p className="text-xs text-amber-500">★ {product.rating}</p>
        </div>
      </div>
    </div>
  )
}

export default function App() {
  // ① 页面要记住的值(state)
  const [query, setQuery] = useState("")
  const [category, setCategory] = useState("全部")
  const [sort, setSort] = useState("recommended")
  const [page, setPage] = useState(1)

  // ② 要显示的商品:筛选 → 排序 → 分页
  const filtered = products.filter((product) => product.name.includes(query) && (category === "全部" || product.category === category))

  // 价格从低到高
  let sorted = filtered
  if (sort === "cheap") sorted = [...filtered].sort((a, b) => a.price - b.price)

  // 价格从高到低
  if (sort === "expensive") sorted = [...filtered].sort((a, b) => b.price - a.price)

  // 评分从高到低
  if (sort === "rating") sorted = [...filtered].sort((a, b) => b.rating - a.rating)

  // 根据筛选后的数量计算总页数
  const totalPages = Math.ceil(sorted.length / pageSize)

  // 第1页 → slice(0, 6),第2页 → slice(6, 12)
  const shown = sorted.slice((page - 1) * pageSize, page * pageSize)

  //console.log(query, category, shown)

  return (
    <div className="mx-auto my-6 w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground">
      {/* 搜索和排序 */}
      <div className="flex flex-wrap items-center gap-2">
        {/* 输入框左侧的线条放大镜图标 */}
        <div className="relative flex-1">
          <SearchIcon className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
          <Input value={query}
        onChange={(e) => {
        setQuery(e.target.value)
        setPage(1) 
        // 搜索后回到第1页
        }}
        className="pl-9" placeholder="搜索商品名称" />
        </div>
        <Select value={sort} onValueChange={(value) => 
        {
        setSort(value)
        setPage(1)
        // 切换排序后回到第1页
        }}>
          <SelectTrigger className="w-40">
            <SelectValue />
          </SelectTrigger>
          <SelectContent position="popper">
            <SelectItem value="recommended">综合推荐</SelectItem>
            <SelectItem value="cheap">价格从低到高</SelectItem>
            <SelectItem value="expensive">价格从高到低</SelectItem>
            <SelectItem value="rating">评分最高</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* 分类 */}
      <div className="mt-3 flex flex-wrap gap-2">
        {categories.map((name) => (
          <Button key={name} size="sm" variant={ category === name ? "default" : "outline" } onClick={() => {
            setCategory(name)
            setPage(1) // 切换分类后回到第1页
          }} 
          className="rounded-full">
            {name}
          </Button>
        ))}
      </div>

      <p className="mt-4 text-xs text-muted-foreground">共 {sorted.length} 件</p>

      {/* 商品卡片 */}
      {sorted.length === 0 ? ( <p className="py-10 text-center text-sm text-muted-foreground">没有找到相关商品</p> ) : (
      <div className="mt-2 grid grid-cols-2 gap-3 sm:grid-cols-3">
        {shown.map((product) => (
        <ProductCard key={product.id} product={product} />
        ))}
      </div>
      )}

      {/* 分页 */}
      <div className="mt-5 flex items-center justify-center gap-1">
        <Button size="sm" variant="outline" disabled={page === 1} onClick={page === 1 ? undefined : () => setPage(page - 1)}>
          上一页
        </Button>
        {Array.from({ length: totalPages }, (_, i) => i + 1).map
        ((number) => (
          <Button key={number} size="sm" variant={page === number ? "default" : "outline"} onClick={() => setPage(number)}>
            {number}
          </Button>
        ))}
        <Button size="sm" variant="outline" disabled={page >= totalPages} onClick={() => setPage(page + 1)}>
          下一页
        </Button>
      </div>
    </div>
  )
}