【问题标题】:React prepend item to listReact 将项目添加到列表中
【发布时间】:2018-09-03 01:41:12
【问题描述】:

我正在尝试将一个项目添加到列表中:

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>

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

【问题讨论】:

  • people: {[newPerson].concat(this.state.people)} 你已经用大括号括起来了。是在实际代码中,还是在发布时出现拼写错误?此外,看起来所有新人都会获得相同的 id;这是故意的吗?
  • key 使用唯一值,一切都会好起来的

标签: javascript reactjs prepend


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 回调有什么区别......仍然在它里面改变原始?使用 slice() 或 spread 可以防止 original 的突变
    • 你是对的 - 基于 setState(callback) 的方法在这里没有任何附加值。感谢您提出的改进建议 :-)
    【解决方案3】:

    尝试这样,在一个新的数组变量中获取状态并将新对象推入其中,最后更新状态。

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

    【讨论】:

    • 通常更好的做法是不要直接改变状态
    【解决方案4】:
    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 2020-06-23
      • 2019-11-29
      • 2017-09-19
      相关资源
      最近更新 更多