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

ReactJS开发食谱盒子应用时输入名称触发TypeError问题

Fixing the TypeError When Entering Recipe Name

Hey there, let’s break down why you’re hitting that TypeError when typing a recipe name and how to fix it.

Root Cause

The problem lies in your handleNameChange function. Right now, when you update the recipe name, you’re replacing the entire productInputValues state object with just { name: event.target.value }. This wipes out the products array that your renderInputs function depends on. When renderInputs tries to access this.state.productInputValues.products[i], products is now undefined—leading directly to the TypeError.

Solution: Merge State Instead of Overwriting

Instead of replacing the whole productInputValues object, you need to preserve existing properties (like the products array) while updating only the name field. Here’s the corrected handleNameChange:

handleNameChange(event) {
  this.setState(prevState => ({
    productInputValues: {
      ...prevState.productInputValues, // Keep existing properties intact
      name: event.target.value // Update only the recipe name
    }
  }));
}

Bonus Fix: Avoid Direct State Mutation

Another issue in your code is that handleChange mutates the state directly, which can cause unexpected React behavior. Let’s fix that by creating a copy of the products array before modifying it:

handleChange(i, event) {
  this.setState(prevState => {
    // Create a copy of the products array to avoid mutating state directly
    const updatedProducts = [...prevState.productInputValues.products];
    updatedProducts[i] = event.target.value;
    return {
      productInputValues: {
        ...prevState.productInputValues,
        products: updatedProducts
      }
    };
  });
}

Why This Works

  • Using prevState in setState ensures we’re working with the most current state, critical if multiple updates happen quickly.
  • Spreading ...prevState.productInputValues preserves all existing properties (like products) while updating only what’s needed.
  • Copying the products array avoids direct state mutation, a core React best practice that prevents bugs and ensures proper re-renders.

With these changes, typing the recipe name won’t erase your products array anymore, and renderInputs will have the products property it needs—eliminating the TypeError entirely.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:51:13