旧版react-redux/react-router下获取ingredients报错排查求助
旧版react-redux/react-router下的代码问题分析
1. Main组件传递props的逻辑错误
Main组件在root.render(<Main />)中未接收任何传入的props,直接使用props.ingredients和props.totalPrice必然返回undefined,传给OrderSummary会触发Cannot read properties of undefined错误。Main作为顶层组件,未通过connect连接Redux Store,根本无法获取store中的状态数据。
2. Reducer中的拼写错误
在reducer的ADD_INGREDIENT分支里存在拼写错误:
[action.ingredienName]: state.ingredients[action.ingredientName] + 1
action.ingredienName少了字母t,正确应为action.ingredientName。该错误会导致无法正确更新配料数量,进而引发state not found或属性读取失败的问题。
3. BurgerBuilder组件的props映射不匹配
mapStateToProps中返回的状态字段是price: state.totalPrice,但组件内使用的是props.totalPrice,字段名称不匹配,会导致BurgerControls的totalprice属性拿到undefined。
4. OrderSummary组件的状态获取方式错误
OrderSummary需要的配料和总价应直接从Redux Store获取,而非通过Main组件传递。正确做法是给OrderSummary添加connect映射:
// OrderSummary.jsx import { connect } from "react-redux"; function OrderSummary(props) { // 直接使用props.ingredients和props.totalPrice } const mapStateToProps = (state) => { return { ingredients: state.ingredients, totalPrice: state.totalPrice }; }; export default connect(mapStateToProps)(OrderSummary);
之后在main.jsx的路由中直接使用组件即可,无需手动传参:
<Route path="/burger-builder/order-page" exact element={<OrderSummary />} />
内容的提问来源于stack exchange,提问作者Mirzaei
相关产品推荐
相关产品推荐

