React-router-dom v6 电商产品路由循环切换需求求助
React Router v6 实现产品页面循环切换(Prev/Next按钮)
核心实现思路
- 从路由参数中获取当前产品ID
- 在预定义的产品ID数组中定位当前ID的索引
- 通过取模运算实现循环切换逻辑(最后一个产品的下一个是第一个,第一个的上一个是最后一个)
- 使用
useNavigate钩子更新路由完成页面跳转
完整代码示例
假设你的路由配置已设置为/combo/:productId,以下是产品页面组件的实现:
import { useParams, useNavigate } from 'react-router-dom'; const ProductPage = () => { // 预定义的产品ID数组 const productIds = [ 'prod_G6kVw7pV6Oo2eD', 'prod_RyWOwmPkL9lnEa', 'prod_ypbroE9QBno8n4', 'prod_Kvg9l61rEm51bB', 'prod_NqKE50NEPBwdgB', 'prod_kpnNwA1P8awmXB' ]; // 获取路由中的产品ID参数 const { productId } = useParams(); // 获取导航钩子 const navigate = useNavigate(); // 定位当前产品在数组中的索引,找不到则默认取第一个 const currentIndex = productIds.findIndex(id => id === productId); const validIndex = currentIndex === -1 ? 0 : currentIndex; // 计算上一个/下一个产品的索引(循环逻辑) const nextIndex = (validIndex + 1) % productIds.length; const prevIndex = (validIndex - 1 + productIds.length) % productIds.length; // 跳转处理函数 const handlePrev = () => { navigate(`/combo/${productIds[prevIndex]}`); }; const handleNext = () => { navigate(`/combo/${productIds[nextIndex]}`); }; return ( <div className="product-page"> {/* 产品内容区域 */} <h1>当前产品:{productId}</h1> {/* 切换按钮 */} <button onClick={handlePrev}>Prev</button> <button onClick={handleNext}>Next</button> </div> ); }; export default ProductPage;
关键细节说明
- 循环逻辑:使用取模运算
%确保索引始终在数组范围内,避免越界。比如最后一个索引(5)加1后取模6得到0,实现从最后一个跳转到第一个;第一个索引(0)减1后加6再取模6得到5,实现从第一个跳转到最后一个。 - 异常处理:如果路由中的产品ID不在预定义数组中,默认跳转到第一个产品,避免出现找不到索引的情况。
- 路由配置:确保你的路由规则正确设置了参数,比如在
Routes中添加:<Route path="/combo/:productId" element={<ProductPage />} />
内容的提问来源于stack exchange,提问作者Simon Buryat
相关产品推荐
相关产品推荐

