如何通过React Context传递all_product到ShopCategory.jsx?分类无内容问题
问题分析与解决方案
核心问题
你的代码中没有在App组件中用ShopContextProvider包裹整个应用的路由内容,导致ShopCategory组件通过useContext(ShopContext)无法获取到all_product数据,all_product会是undefined,后续的map遍历不会执行,因此页面没有内容展示。
修复步骤
1. 修改App.js,添加ShopContextProvider包裹
首先在App.js中导入ShopContextProvider,然后将Router内部的所有组件(Navbar、Routes、Footer)包裹在ShopContextProvider中:
import './App.css'; import React from 'react'; import { Navbar } from './Components/Navbar/Navbar'; import { BrowserRouter as Router,Routes,Route } from 'react-router-dom'; import ShopCategory from './Pages/ShopCategory'; import { Product } from './Pages/Product'; import { Shop } from './Pages/Shop'; import { LoginSignup } from './Pages/LoginSignup'; import {Cart} from './Pages/Cart'; import { Footer } from './Components/Footer/Footer'; import men_banner from './Components/Assets/banner_mens.png' import women_banner from './Components/Assets/banner_women.png' import kid_banner from './Components/Assets/banner_kids.png' // 导入ShopContextProvider import ShopContextProvider from './Context/ShopContext'; function App() { return ( <div> <ShopContextProvider> {/* 包裹整个路由内容 */} <Router> <Navbar/> <Routes> <Route path='/' element={<Shop/>}/> <Route path='/mens' element={<ShopCategory banner={men_banner} category="mens"/>}/> <Route path='/womens' element={<ShopCategory banner={women_banner} category="womens"/>}/> <Route path='/kids' element={<ShopCategory banner={kid_banner} category="kids"/>}/> <Route path="/product" element={<Product/>}> <Route path=":productId" element={<Product/>}/> </Route> <Route path='/cart' element={<Cart/>}/> <Route path='/login' element={<LoginSignup/>}/> </Routes> <Footer/> </Router> </ShopContextProvider> </div> ); } export default App;
2. 验证分类字段匹配
确保all_product数组中每个item的category字段值,和你传入ShopCategory的category prop完全一致(包括大小写、拼写)。比如:
- 如果传入的是
category="mens",那数据里的item.category必须也是"mens",不能是"Men"或"Mens",否则条件判断props.category === item.category不成立,不会渲染对应商品。
3. 可选:添加数据兜底处理
为了避免all_product未加载时出现报错,可以在ShopCategory中添加兜底逻辑:
<div className="shopcategory-products"> {all_product ? ( all_product.map((item,i) => { if (props.category === item.category) { return <Item key={i} id={item.id} name={item.name} image={item.image} new_price={item.new_price} old_price={item.old_price} />; } return null; }) ) : ( <p>暂无商品数据</p> )} </div>
内容的提问来源于stack exchange,提问作者HAREESH
相关产品推荐
相关产品推荐

