代码
........
........
state = {
users: [],
currentUser: '',
currentAge: '',
};
........
........
onSubmitHandler = (e) => {
const Person = {
name: this.state.currentUser, //already assign in another function
age: this.state.currentAge,//already assign in another function
};
this.setState({
users: [...this.state.users, Person],
});
};
render() {
return (
<div>
<h1></h1>
<form onSubmit={this.onSubmitHandler}>
<label>
Enter your name:
<input type="text" onChange={this.onChangeNameHandler} />
</label>
<br />
<label>
Enter your Age:
<input type="number" onChange={this.onChangeAgeHandler} />
</label>
<br />
<input type="submit" />
</form>
<ul>
{this.state.users.map((user) => {
return <UserCard name={user.name} age={user.age} />;
})}
</ul>
</div>
);
}
}
错误
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `UserForm`. See https://reactjs.org/link/warning-keys for more information.
at UserCard (https://react-3agtbk.stackblitz.io/~/src/components/UserCard.js:7:1)
at UserForm (https://react-3agtbk.stackblitz.io/~/src/components/UserForm.js:10:9)
at div
at App
我正在尝试将Person对象添加到users数组中。但是,当我尝试console.log(this.state.users(时,它总是显示[]。我确实在onSubmitHandler函数中添加了preventDefault,从而解决了这个问题。在我的另一个项目中,我没有添加onSubmitHandler,它仍然有效。为什么会这样?提前谢谢。
两个问题:
-
onSubmitHandler
中没有任何内容阻止提交的默认操作,即将表单提交到服务器,并用服务器的结果完全替换页面。您需要添加对
e.preventDefault()
的调用,以阻止提交的默认操作。 -
您的
setState
呼叫应该使用回调版本:this.setState(({users, currentUser, currentAge}) => { const Person = { name: currentUser, age: currentAge, }; return {users: [...users, Person]}; });
这是在您基于现有状态更新状态时的最佳实践。
此外,附带说明的是,JavaScript代码中最初有上限的变量名几乎都是为构造函数保留的。仅引用对象的局部变量的绝大多数标准约定是使用初始小写(person
,而不是Person
(。
把所有这些放在一起:
onSubmitHandler = (e) => {
e.preventDefault();
this.setState(({users, currentUser, currentAge}) => {
const person = {
name: currentUser,
age: currentAge,
};
return {users: [...users, person]};
});
};