javascript - React 将项目添加到列表中
问题描述
我正在尝试将一个项目添加到列表中:
addPersonHandler = () => {
const newPerson = {
id: "new",
edit: true,
name: "",
dni: "",
onDelete: this.discardHandler
};
// I want to prepend the new person to the people list.
this.setState({addingPerson: true, people: {[newPerson].concat(this.state.people)});
}
但它总是最后渲染!
<ul>
People.map((p, i) => {
return <li key={p.id}>
<Person
id={p.id}
name={p.name}
dni={p.dni}
onDelete={p.id=="new"? this.discardHandler: this.deleteHandler}
edit={p.edit}
/>
</li>
});
</ul>
我真的不知道为什么如果我将它添加到列表的开头它最后呈现...
解决方案
您可以在原始数组上使用扩展并删除{}
包装新数组
this.setState({addingPerson: true, people: [newPerson, ...this.state.people]);
推荐阅读
- mysql - 在mysql中使用纪元日期检索记录
- firebase - 我使用 Firebase Flutter 中的提供程序连接到我的应用程序
- java - 如何在 Spring Cloud Contract Groovy DSL Contract 定义中将请求主体对象属性定义为可为空?
- python - 如何计算列表中特定类型的出现次数?
- python - 在 PysimpleGUI 的输入中输入文本后,如何自动将光标置于输入文本的末尾?
- c# - 模型不绑定在 POST 控制器方法.Net Core MVC
- c# - AES 大块解密在末尾添加随机字节
- azure - Azure 计算机视觉为带有矢量图形的 pdf 返回垃圾
- reactjs - Webpack 5 无法解析图片
- python - 当我希望它成为日期时,继续将 dtypes 作为对象