首页 > 解决方案 > 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>

我真的不知道为什么如果我将它添加到列表的开头它最后呈现...

标签: javascriptreactjsprepend

解决方案


您可以在原始数组上使用扩展并删除{}包装新数组

this.setState({addingPerson: true, people: [newPerson, ...this.state.people]);

推荐阅读