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

React购物车页面空白问题求助:传递函数Props后无法渲染

购物车页面空白问题的解决方案

问题背景

我正在开发一个包含商品数组的购物页面,已经实现了addToCart、removeFromCart、increaseQuantity和decreaseQuantity等函数。但将这些函数作为props传递给Cart页面后,点击导航栏的Cart选项时页面无法正常渲染,显示空白屏幕。尽管通过console.log检查相关方法,仍无法确定问题根源。

核心问题分析

  1. 状态作用域错误:购物车状态cartItems和操作函数定义在Shop组件内部,当通过路由跳转到独立的Cart页面时,Shop组件不会被渲染,导致Cart组件接收不到cartItems和操作函数的props,进而因为cartItems为undefined,执行map时引发错误,页面空白。
  2. 路由大小写不匹配:导航栏中Cart的路径是/Cart,但App路由配置的是/cart,大小写不一致会触发通配符路由(*),而ErrorPage组件未导入,导致页面空白。
  3. App.js语法错误:路由配置里多了一个多余的<符号,会导致组件渲染失败。

分步解决方案

1. 修复App.js的语法和路由问题

将购物车状态和操作函数提升到App组件,实现跨组件共享,同时修复语法错误:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { useState } from 'react';
import Shop from './Components/Pages/A-Shop/Shop';
import Cart from './Components/Pages/Cart';
import NavBar from './Components/NavBar';

function App() {
  // 提升购物车状态到App组件
  const [cartItems, setCartItems] = useState([]);

  const addToCart = (item) => {
    const index = cartItems.findIndex((cartItem) => cartItem.id === item.id);
    if (index === -1) {
      setCartItems([...cartItems, { ...item, quantity: 1 }]);
    } else {
      const newCartItems = [...cartItems];
      newCartItems[index].quantity++;
      setCartItems(newCartItems);
    }
  };

  const removeFromCart = (item) => {
    const newCartItems = [...cartItems];
    const index = newCartItems.findIndex((cartItem) => cartItem.id === item.id);
    newCartItems.splice(index, 1);
    setCartItems(newCartItems);
  };

  const increaseQuantity = (item) => {
    const newCartItems = [...cartItems];
    const index = newCartItems.findIndex((cartItem) => cartItem.id === item.id);
    newCartItems[index].quantity++;
    setCartItems(newCartItems);
  };

  const decreaseQuantity = (item) => {
    const newCartItems = [...cartItems];
    const index = newCartItems.findIndex((cartItem) => cartItem.id === item.id);
    if (newCartItems[index].quantity > 1) {
      newCartItems[index].quantity--;
      setCartItems(newCartItems);
    }
  };

  return (
    <div className='App'>
      <Router>
        <NavBar />
        <Routes>
          {/* 修复多余的<符号,传递addToCart给Shop */}
          <Route path='/Shop' element={<Shop addToCart={addToCart} />} />
          {/* 传递购物车状态和操作函数给Cart */}
          <Route path='/cart' element={<Cart 
            cartItems={cartItems}
            removeFromCart={removeFromCart}
            increaseQuantity={increaseQuantity}
            decreaseQuantity={decreaseQuantity}
          />} />
          {/* 暂时注释未定义的ErrorPage路由 */}
          {/* <Route path='*' element={<ErrorPage />} /> */}
        </Routes>
      </Router>
    </div>
  );
}

export default App;

2. 统一路由路径大小写

修改NavBar中Cart的路径,和App路由配置匹配:

// NavBar.js中调整Cart的路径
<NavItem to='/cart' label='Cart' />

3. 调整Shop组件,移除内部状态

Shop组件不再维护购物车状态,仅接收addToCart函数:

function Shop({ addToCart }) {
    const items = [
        { id: 1, name: 'T-shirt', price: 25, image: 'images/Shop/6.png' },
        { id: 2, name: 'Patch', price: 10, image: 'images/Shop/4.PNG' },
        { id: 3, name: 'Cap', price: 20, image: 'images/Shop/3.png' },
        { id: 4, name: 'Bandana', price: 15, image: 'images/Shop/2.png' },
        { id: 5, name: 'Bag', price: 20, image: 'images/Shop/1.png' },
        { id: 6, name: 'Socks', price: 20, image: 'images/Shop/5.png' }
    ];

    return (
        <div className='Shop'>
            <h1 className='shop-title'>Shopping Page</h1>
            <div className="item-list">
                {items.map((item) => (
                    <div key={item.id} className="item">
                        <img className='shop-image' src={item.image} alt={item.name} />
                        <h2>{item.name}</h2>
                        <p>£{item.price}</p>
                        <button className='shop-button' onClick={() => addToCart(item)}>Add to Cart</button>
                    </div>
                ))}
            </div>
            {/* 移除Shop内部渲染的Cart组件,改为路由跳转 */}
        </div>
    );
}

export default Shop;

4. 优化Cart组件,处理空数组场景

避免空数组或undefined时的渲染异常:

const Cart = (props) => {
    const { cartItems, removeFromCart, increaseQuantity, decreaseQuantity } = props;

    return (
        <div className='Cart'>
            <h1 className='cart-title'>Cart Page</h1>
            <div className="cart-items">
                {cartItems.length === 0 ? (
                    <p>购物车是空的,快去挑选商品吧!</p>
                ) : (
                    cartItems.map((item) => (
                        <div key={item.id} className="cart-item">
                            <img className='cart-image' style={{ width: "100px", height: "100px" }} src={item.image} alt={item.name} />
                            <h2>{item.name}</h2>
                            <p>£{item.price}</p>
                            <p>Quantity: {item.quantity}</p>
                            <button className='cart---button' onClick={() => increaseQuantity(item)}>+</button>
                            <button className='cart---button' onClick={() => decreaseQuantity(item)}>-</button>
                            <button className='cart-remove-button' onClick={() => removeFromCart(item)}>Remove</button>
                        </div>
                    ))
                )}
            </div>
        </div>
    );
};

export default Cart;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:54:57