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

旧版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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:43:09