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

React点击分类按钮更新API URL并刷新商品列表问题求助

解决点击分类按钮更新商品列表的问题

原代码核心问题

  • useEffect的依赖数组为空,只会在组件首次挂载时发起一次API请求,切换分类后不会重新请求数据
  • 顶部banner显示的始终是初始传入的category值,没有同步更新选中的分类

修复方案

  1. 让useEffect监听分类变化:把cat1加入useEffect的依赖数组,每次分类切换时自动重新请求对应分类的商品数据
  2. 同步更新banner标题:将banner中的{category}替换为{cat1},保证标题和当前选中分类一致
  3. 优化API地址拼接:直接在fetch中处理分类路径,减少冗余变量

修改后的完整代码

import React, { useEffect, useState } from 'react'
import './Allproducts.css'
import ForYouItem from './ForYouItem'

export default function Allproducts(props) {
    const [products, setProducts] = useState([]);
    const { category } = props;
    const [cat1, setCat1] = useState(category);
    // 可选:添加加载状态,提升用户体验
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        setIsLoading(true);
        fetch(`https://fakestoreapi.com/products/category/${cat1}`)
            .then((res) => res.json())
            .then((data) => setProducts(data))
            .catch((err) => console.error('商品请求失败:', err))
            .finally(() => setIsLoading(false));
    }, [cat1]) // 监听分类值变化,触发重新请求

    const ChangeRoute = (c) => {
       setCat1(c);
    }

    return (
        <>
            <div className="banner">
                <h1>{cat1}</h1>
                <h4>Get best items in budget</h4>
            </div>
            <div className="main-grid">
                <div className="left-grid">
                    <div className="left-categories">
                        <h1>Collections</h1>
                         <h4 className='products-categories' onClick={() => ChangeRoute("electronics")}>electronics</h4>
                         <h4 className='products-categories' onClick={() => ChangeRoute("jewelery")}>jewelery</h4>
                         <h4 className='products-categories' onClick={() => ChangeRoute("men's clothing")}>men's clothing</h4>
                         <h4 className='products-categories' onClick={() => ChangeRoute("women's clothing")}>women's clothing</h4>
                    </div>
                </div>

                <div className="right-grid">
                    {isLoading ? (
                        <div>加载中...</div>
                    ) : (
                        <div className="row ">
                            {products.map((product) => (
                                <div className="col-md-4 my-2 Products" key={product.id}>
                                    <ForYouItem 
                                        Title={product.title.slice(0, 21)} 
                                        Price={product.price} 
                                        Imageurl={product.image} 
                                        rate={product.rating.rate} 
                                        count={product.rating.count} 
                                    />
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </>
    )
}

额外说明

  • 增加了isLoading状态处理,切换分类时显示加载提示,避免用户看到空白列表
  • 在map循环中添加了key={product.id},符合React列表渲染规范,避免控制台警告
  • 加入了catch捕获请求错误,方便调试接口问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:45:19