React项目报错:未找到addToCart默认导出及useHistory替代疑问
问题解决指南
1. 导出/导入不匹配报错解决
报错原因:cartActions.js中使用命名导出export const addToCart,但CartScreen.js里用了默认导入import addToCart from '../actions/cartActions',两者不匹配导致报错。
修改方法:
将CartScreen中的导入语句改为命名导入:
// 替换原来的默认导入 import { addToCart } from '../actions/cartActions'
2. useHistory弃用后的替换方案
在react-router-dom v6版本中,useHistory已被移除,取而代之的是useNavigate钩子,同时组件不再通过props接收match、location、history,需用专门钩子获取路由信息:
步骤1:导入所需钩子
import { Link, useParams, useLocation, useNavigate } from "react-router-dom";
步骤2:替换props获取路由信息
// 移除组件参数中的match, location, history function CartScreen() { // 使用useParams获取URL参数 const { id: productId } = useParams(); // 使用useLocation获取查询参数 const location = useLocation(); const qty = location.search ? Number(location.search.split("=")[1]) : 1; // 使用useNavigate替代useHistory const navigate = useNavigate(); // 后续逻辑保持不变 }
步骤3:跳转逻辑替换(若有需要)
如果之前有类似history.push('/path')的跳转代码,替换为:
navigate('/path');
额外代码问题修复
你的CartScreen代码还有两处小问题需要修正:
- map循环未返回组件,导致购物车项无法渲染,需添加
return(或改用括号包裹组件) item.Image应为item.image(与cartActions中的payload字段命名一致)
修改后的完整CartScreen.js代码
import React, { useEffect } from "react"; import { Link, useParams, useLocation, useNavigate } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import { Row, Col, ListGroup, Form, Image, Button, Card, } from "react-bootstrap"; import Message from "../components/Message"; import { addToCart } from "../actions/cartActions"; function CartScreen() { const { id: productId } = useParams(); const location = useLocation(); const qty = location.search ? Number(location.search.split("=")[1]) : 1; const navigate = useNavigate(); const dispatch = useDispatch(); const cart = useSelector((state) => state.cart); const { cartItems } = cart; useEffect(() => { if (productId) { dispatch(addToCart(productId, qty)); } }, [dispatch, productId, qty]); return ( <Row> <Col md={8}> <h1>Shopping Cart</h1> {cartItems.length === 0 ? ( <Message variant="info"> Your cart is empty <Link to="/"> Go Back</Link> </Message> ) : ( <ListGroup variant="flush"> {cartItems.map((item) => ( <ListGroup.Item key={item.product}> <Row> <Col md={2}> <Image src={item.image} alt={item.name} fluid rounded /> </Col> <Col md={3}> <Link to={`/product/${item.product}`}>{item.name}</Link> </Col> <Col md={2}>${item.price}</Col> </Row> </ListGroup.Item> ))} </ListGroup> )} </Col> <Col md={4}></Col> </Row> ); } export default CartScreen;
内容的提问来源于stack exchange,提问作者ToddM
相关产品推荐
相关产品推荐

