React报错:数组或迭代器子元素需唯一"key"属性 附Form组件代码
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:
- Update your input fields to include
nameprops:
<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" />
- Rewrite
handleChangeto 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

