在组件状态下从数组中删除元素 [英] Removing element from array in component state

查看:41
本文介绍了在组件状态下从数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到从处于组件状态的数组中删除元素的最佳方法.由于我不应该直接修改 this.state 变量,有没有比我这里更好的方法(更简洁)从数组中删除元素?:

I am trying to find the best way to remove an element from an array in the state of a component. Since I should not modify the this.state variable directly, is there a better way (more concise) to remove an element from an array than what I have here?:

  onRemovePerson: function(index) {
    this.setState(prevState => { // pass callback in setState to avoid race condition
      let newData = prevState.data.slice() //copy array from prevState
      newData.splice(index, 1) // remove element
      return {data: newData} // update state
    })
  },

谢谢.

更新

这已更新为使用 setState 中的回调.这应该在更新它时引用当前状态时完成.

This has been updated to use the callback in setState. This should be done when referencing the current state while updating it.

推荐答案

我见过的最简洁的方法是使用 filter:

The cleanest way to do this that I've seen is with filter:

removeItem(index) {
  this.setState({
    data: this.state.data.filter((_, i) => i !== index)
  });
}

这篇关于在组件状态下从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆