我正在尝试将商品添加到列表的前面:
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>
我真的不知道为什么要把它添加到列表的开头,为什么最后显示...
答案 0 :(得分:2)
您可以在原始数组上使用展开,并删除Btnsubmit.enabled=false
包装新数组的
{}
答案 1 :(得分:0)
像这样尝试,在一个新的数组变量中获取状态并将新对象推入其中,最后更新状态。
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 });
};
答案 2 :(得分:0)
考虑the unshift()
method,您可以使用它在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 });
}
答案 3 :(得分:0)
<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>