我正在尝试将项目附加到列表中:
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]);
考虑unshift()
方法,您可以使用该方法将一个或多个元素附加到people
数组。
请记住,unshift()
方法会改变调用它的数组:
addPersonHandler = () => {
const newPerson = {
id: "new",
edit: true,
name: "",
dni: "",
onDelete: this.discardHandler
};
// Get people array from current state
const people = this.state.people;
// Prepends the newPerson to the start of people array
people.unshift(newPerson);
// Return the updated state to your component for re-render
this.setState({ addingPerson : true, people : people });
}
尝试这样,在一个新的数组变量中获取状态并将新对象推送到其中,最后更新状态。
addPersonHandler = () => {
const newPerson = {
id: "new",
edit: true,
name: "",
dni: "",
onDelete: this.discardHandler
};
let pplArr = this.state.people;
pplArr.push(newPerson);
this.setState({ addingPerson: true, people: pplArr });
};
<ul>
<Person
id={p.id}
name={p.name}
dni={p.dni}
onDelete={p.id=="new"? this.discardHandler: this.deleteHandler}
edit={p.edit}
/>
People.map((p, i) => {
return <li key={p.id}>
</li>
});
</ul>