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

React useReducer开发食谱盒输入触发报错:无法读取undefined的ingredients属性

问题

学习React的useReducer时开发了一个食谱盒,支持通过文本输入框修改食材的名称、计量单位和数量。但输入时整个食材列表会消失,同时出现以下错误:

TypeError: Cannot read properties of undefined (reading 'ingredients')
at App (pen.js:63:26)
at Bi (react-dom.js:7:19481)
at ei (react-dom.js:9:3150)
at oa (react-dom.js:9:44778)
at la (react-dom.js:9:39715)
at pf (react-dom.js:9:39646)
at Ir (react-dom.js:9:39506)
at so (react-dom.js:9:36651)
at on (react-dom.js:7:3250)
at Gi (react-dom.js:9:36960)

触发输入操作后,recipe参数会变为undefined,此前功能正常。

解决方案

问题根源

错误出在useReducer的reducer函数中,部分action处理逻辑没有正确返回完整的state结构。比如在处理食材更新的action时,直接返回了修改后的recipe对象,而非将其嵌套在原state的recipe属性下,导致后续组件读取state.recipe.ingredients时,state.recipe变为undefined。

修复步骤

  1. 修正reducer的case分支返回值:确保每个case都返回包含recipe属性的完整state对象,而非单独的recipe。
    错误示例:

    case UPDATE_INGREDIENT:
      const updatedRecipe = { ...state.recipe, ingredients: /* 修改后的食材数组 */ };
      return updatedRecipe; // 直接返回recipe,丢失外层state结构
    

    修正后:

    case UPDATE_INGREDIENT:
      const updatedRecipe = { ...state.recipe, ingredients: /* 修改后的食材数组 */ };
      return { ...state, recipe: updatedRecipe }; // 保留原state结构,仅更新recipe属性
    
  2. 确保所有action返回结构一致:reducer始终返回与初始state结构匹配的对象,避免因结构不匹配导致属性读取失败。

  3. 添加default分支返回当前state:防止未匹配到action时返回undefined:

    default:
      return state;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:10:47