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

React-Router-Dom v6下CartItems路由报/products/undefined 500错误

问题原因

点击导航栏购物车链接时匹配的是/cart的index路由,这个路由下没有productid参数,值为undefined。但CartScreen组件的副作用逻辑没有判断参数是否存在,直接调用addToCart action发起接口请求,最终请求地址变成/products/undefined,触发500服务端错误,同时异步请求没有做异常捕获,才会抛出Uncaught (in promise)错误。

修复方案
  • 修改CartScreen.js的副作用逻辑,仅当路由携带合法商品id时才触发添加购物车的dispatch操作:
// CartScreen.js 中的useEffect替换为以下代码
useEffect(() => {
  if (productid) {
    dispatch(addToCart(productid, qty));
  }
},[dispatch, productid, qty]);
  • 给cartAction.js中的异步逻辑增加参数校验和异常捕获,从源头拦截非法请求,避免未捕获的promise报错:
// cartAction.js 中addToCart方法替换为以下代码
export const addToCart = (productid, qty) => async (dispatch, getState) => {
  if (!productid) return;
  try {
    const { data } = await axios.get(`/products/${productid}`);

    dispatch({
      type: CART_ADD_ITEM,
      payload: {
        product: data._id,
        name: data.name,
        image: data.image,
        price: data.price,
        countInStock: data.countInStock,
        qty,
      },
    });

    localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems));
  } catch (error) {
    // 可按需接入错误提示逻辑
    console.error('加入购物车失败:', error);
  }
};
  • 修复隐藏bug:ProductScreen.js中使用了useState、useEffect两个React Hook,但没有从react包中导入,需要补充导入语句,否则运行时会报Hook未定义错误:
// 在ProductScreen.js顶部补充导入
import { useState, useEffect } from 'react';
错误截图参考

错误截图

内容的提问来源于stack exchange,提问作者rafee muhammed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:57:11