【问题标题】:React - Deleting from middle of list removes last element insteadReact - 从列表中间删除会删除最后一个元素
【发布时间】:2015-09-18 18:18:55
【问题描述】:

我正在使用 React 开发一个简单的练习应用程序。我有四个组件:一个将用户作为对象存储在数组中的主组件,一个呈现每个用户信息的 userView 组件,一个呈现所有 userViews 的 userList 组件,以及一个在提交时将新用户添加到主组件的 addUser 组件。在列表中添加和编辑项目可以正常工作。但是,我遇到了删除问题。每个列表项都有自己的删除按钮,应该删除该元素,但无论使用哪个删除按钮,列表中的最后一个元素都会被删除。我正在使用 splice 从包含 Main 中的用户的数组中删除,并且我检查了当按下删除按钮时 splice 是否传递了正确的索引。

我认为这与虚拟 DOM 重新呈现时组件上的键有关,但我尝试使用几种不同的方法(component.id、全局计数器变量、数组中的索引)添加键并且仍然有没运气。以下是相关的代码(为简洁起见,我尽可能多地省略了):

var Main = React.createClass({
  getInitialState: function(){
    return {
      allUsers: []
    }
  },
  removeUser: function(index){
    console.log('index to remove at: ', index); //Gives correct index
    var newUsersArray = this.state.allUsers.slice();
    newUsersArray.splice(index, 1);
    this.setState({
      allUsers: newUsersArray
    });
  },
  render: function(){
    return (
      <div>
        <AddUser addNew={this.addUser} index={this.state.allUsers.length} />
        <UserList users={this.state.allUsers} edit={this.editUser} remove={this.removeUser} />
      </div>
  )
  }
})

  var UserList = React.createClass({
    render: function(){
      var users = this.props.users;
      var edit = this.props.edit;
      var remove = this.props.remove;
      return (
        <div>
        {users.map(function(user){
          return <UserView userName={user.name} userRoles={user.roles} editUser={edit} remove={remove} key={user.id} index={user.index}/>
    })}
       </div>
      );
    }
});

var UserView = React.createClass({
  handleDelete: function(){
    this.props.remove(this.props.index);
});

我遗漏了很多,这是我所有的 React 代码:http://jsfiddle.net/dpdbv731/。基本上,当单击 userView 组件时,它会调用 Main 上的 removeUser 函数,并将该组件的索引作为参数。谁能看到我哪里出错了?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    UserView 上的键未定义 - user 上没有 id 字段。这会导致 React 回退到使用数组索引作为键。现在,当您删除 2 元素列表中的第 0 项时,将剩下一个组件,其键为“0”。在协调期间,React 会将作为 props 传递的剩余元素与之前具有键“0”的 组件 相关联。换句话说,传递了正确的数组元素,但它与错误的组件相关联,并且由于该组件包含某些状态,因此看起来像是删除了错误的项目。由于在您的示例中每个用户的索引都是唯一的,因此您可以通过将 key={user.index} 添加到 UserView 来解决此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多