在React中如何将项目添加到列表的开头?

4

我想要在列表中添加一个元素:

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>

我真的不知道为什么如果我把它添加到列表的开头,它会最后渲染出来...

这句话与IT技术有关。

2
你把以下的程式碼翻譯成中文:people: {[newPerson].concat(this.state.people)} 這裡用了大括號,請問是原始碼本身就有還是在發布時打錯了呢?此外,看起來所有的新人都會得到相同的ID,這樣是故意的嗎? - Nicholas Tower
使用唯一的值作为 key,所有的东西都会正常。 - marzelin
4个回答

4
您可以在原始数组上使用扩展运算符,并删除包装新数组的 {}
this.setState({addingPerson: true, people: [newPerson, ...this.state.people]);

2
考虑使用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 });
}

回调函数有什么区别...在其中仍然改变原始值?使用slice()或spread可以防止原始值的改变。 - charlietfl
你说得对 - 使用setState(callback)的方法并没有增加任何价值。感谢您提出的改进意见 :-) - Dacre Denny

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 });
    };

1
通常最好的做法是不直接改变状态。 - charlietfl

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接