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

React报错:数组或迭代器子元素需唯一"key"属性 附Form组件代码

Fixing the "Each child in an array or iterator should have a unique 'key' prop" Error in Your React Form Component

Hey there! Let's break down how to fix that frustrating key prop error you're seeing.

First, a quick recap of why this error happens: When React renders elements from an array (like your user state array), it needs a unique key prop on each child element. This helps React efficiently track which items have changed, been added, or removed—without it, React can't optimize re-renders properly, hence the warning.

Looking at your code, you have a user array in your state, so I'm guessing somewhere later in your component (probably in the render method) you're mapping over this array to display user data, but you aren't adding that required key prop.

Example of the Problem (and Fix)

If your render code looks something like this (without a key):

render() {
  return (
    <Jumbotron>
      <form onSubmit={this.handleSubmit}>
        {/* Your input fields here */}
        {this.state.user.map(user => (
          <div>
            <p>First Name: {user.firstname}</p>
            <p>Last Name: {user.lastname}</p>
          </div>
        ))}
        <button type="submit">Submit</button>
      </form>
    </Jumbotron>
  );
}

You need to add a unique key to the root element inside the map function. Ideally, use a unique identifier from your user data (like an id if your API returns one). If you don't have a unique ID, you can use the array index as a last resort (note: this isn't ideal if the array order might change, but it works for simple cases):

{this.state.user.map((user, index) => (
  <div key={user.id || index}> {/* Use user.id if available, else index */}
    <p>First Name: {user.firstname}</p>
    <p>Last Name: {user.lastname}</p>
  </div>
))}

Quick Side Note: Fixing Your handleChange Method

I also noticed a small bug in your handleChange function—right now, you're setting both firstname and lastname to the same input value, which means typing in either field will overwrite both states. To fix this, add name attributes to your input fields and update state dynamically:

  1. Update your input fields to include name props:
<input 
  type="text" 
  name="firstname" 
  value={this.state.firstname} 
  onChange={this.handleChange} 
  placeholder="First Name"
/>
<input 
  type="text" 
  name="lastname" 
  value={this.state.lastname} 
  onChange={this.handleChange} 
  placeholder="Last Name"
/>
  1. Rewrite handleChange to use the input's name:
handleChange = event => {
  const { name, value } = event.target;
  this.setState({ [name]: value });
};

That way, each input updates only its corresponding state property.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:21:10