React Router跳转后URL变更但商品未更新问题求助
问题解决:点击分类链接后URL变化但商品列表不更新
核心问题分析
- 数据请求未监听分类变化:商品数据获取的
useEffect依赖数组为空,仅在组件首次挂载时执行一次。当分类参数(props.category或路由参数)变化时,不会重新发起请求获取对应分类的商品。 - 路由参数与组件状态未关联:如果路由通过
/:category传递分类信息,当前组件未监听路由参数变化,无法触发数据更新逻辑。
解决方案步骤
1. 修复数据请求的依赖监听
将分类参数加入useEffect的依赖数组,确保分类变化时自动重新请求数据:
useEffect(() => { fetch(`https://fakestoreapi.com/products/category/${props.category}`) .then((res) => res.json()) .then((data) => setProducts(data)) }, [props.category]) // 添加props.category到依赖数组
2. 改用路由参数获取分类(更推荐)
如果路由配置为/:category(如/electronics),直接通过useParams获取路由参数,无需依赖props传递:
- 先导入
useParams:
import { Link, useParams } from 'react-router-dom';
- 在组件内获取分类参数:
export default function Allproducts() { const { category } = useParams(); // 获取路由中的category参数 const [products, setProducts] = useState([]); useEffect(() => { fetch(`https://fakestoreapi.com/products/category/${category}`) .then((res) => res.json()) .then((data) => setProducts(data)) }, [category]) // 监听路由参数变化 // ... 其他代码 }
3. 优化分类数据加载(可选)
已导入Categories.json,无需再通过fetch加载,直接使用即可:
const [categories, setCategories] = useState([]); useEffect(() => { setCategories(Categories.title); // 直接使用导入的JSON数据 }, [])
4. 确认路由配置正确
确保路由配置包含对应分类路由:
// 示例路由配置(App.js或路由文件中) import { Routes, Route } from 'react-router-dom'; import Allproducts from './Allproducts'; function App() { return ( <Routes> <Route path="/:category" element={<Allproducts />} /> {/* 其他路由 */} </Routes> ); }
内容的提问来源于stack exchange,提问作者Afeef Raza
相关产品推荐
相关产品推荐

