Next.js+Redux Toolkit动态页面多接口数据动态获取实现方案
解决方案
要实现根据不同路由参数调用对应API并展示数据的需求,可以按以下步骤修改代码:
1. 扩展Redux状态管理(以新增Crops类型为例)
首先为新增的数据类型创建对应的Redux切片,结构参考现有的productCategorySlice:
- 创建
redux/slices/product/cropsSlice.js,实现fetchCrops异步Action,包含loading、error、data等状态字段,确保返回的数据格式和fetchProducts一致(比如都通过data.data存储列表数据)。 - 如果后续需要支持更多类型,只需重复此步骤新增对应切片即可。
2. 修改页面逻辑,根据路由参数分发对应Action
在product/[category]/index.js中,根据router.query.category的值判断调用哪个API:
import React, { useEffect } from "react"; import { ProductCard } from "@components/Product/ProductCategory/ProductList"; import { CropCard } from "@components/Crop/CropCategory/CropList"; // 新增Crop组件引入 import { useDispatch, useSelector } from "react-redux"; import { fetchProducts } from "redux/slices/product/productCategorySlice"; import { fetchCrops } from "redux/slices/product/cropsSlice"; // 新增Crops Action引入 import { useRouter } from "next/router"; const CategoryDetail = () => { const router = useRouter(); const { category } = router.query; const dispatch = useDispatch(); // 根据category获取对应状态 const currentData = useSelector((state) => { switch(category) { case 'crops': return state.crops; case 'products': default: return state.productCategory; } }); // 根据路由参数分发对应Action useEffect(() => { if (!category) return; // 避免路由未加载时触发请求 switch(category) { case 'crops': dispatch(fetchCrops(category)); break; default: dispatch(fetchProducts(category)); break; } }, [dispatch, category]); // 路由参数未加载时的占位提示 if (!category) { return <div className="container max-w-full py-24">加载中...</div>; } return ( <div className="container max-w-full"> <div className="flex flex-row py-24"> <div className="w-80per pl-30"> {/* 加载状态提示 */} {currentData.loading && <div>加载中...</div>} {/* 错误状态提示 */} {!currentData.loading && currentData.error ? <div className="text-red-500">加载失败:{currentData.error}</div> : null} {/* 数据渲染 */} {!currentData.loading && currentData.data?.data ? ( <div className="grid grid-cols-4 gap-5"> {currentData.data.data.map((item) => { const uniqueKey = item.id || item._id; // 使用唯一标识作为key if (category === 'crops') { return <CropCard key={uniqueKey} data={item} modal={false} />; } return <ProductCard key={uniqueKey} data={item} modal={false} />; })} </div> ) : !currentData.loading && <div>暂无数据</div>} </div> </div> </div> ); }; export default CategoryDetail;
3. 后续扩展说明
如果需要支持更多数据类型(比如tools、seeds等),只需:
- 新增对应Redux切片和异步Action
- 引入对应的数据展示组件
- 在
switch分支中添加新的category判断逻辑
关键优化点
- 替换原有的
console.log提示为页面可视化反馈,提升用户体验 - 使用数据的唯一标识(如
id/_id)作为列表项的key,避免React警告 - 增加路由参数未加载时的占位处理,避免空值报错
内容的提问来源于stack exchange,提问作者aysel xudiyeva
相关产品推荐
相关产品推荐

