故事是这样的,我应该可以把鲍勃,莎莉和杰克放进一个盒子里。我也可以把它们从盒子里拿出来。拆卸时,没有插槽留下。

people = ["Bob", "Sally", "Jack"]

现在我需要删除,比如说,“Bob”。新的数组将是:

["Sally", "Jack"]

下面是我的react组件:

...

getInitialState: function() {
  return{
    people: [],
  }
},

selectPeople(e){
  this.setState({people: this.state.people.concat([e.target.value])})
},

removePeople(e){
  var array = this.state.people;
  var index = array.indexOf(e.target.value); // Let's say it's Bob.
  delete array[index];
},

...

这里我向你展示了一个最小的代码,因为有更多的它(onClick等)。关键部分是从数组中删除,删除,销毁“Bob”,但removePeople()在调用时不工作。什么好主意吗?我正在看这个,但我可能做错了,因为我使用React。


当前回答

只需过滤掉已删除的项,并再次用剩余的项更新状态,

let remainingItems = allItems.filter((item) => {return item.id !== item_id});
    
setItems(remainingItems);

其他回答

从react的状态数组中删除项目的简单方法:

当任何数据从数据库中删除和更新列表时,没有调用API,你将删除id传递给这个函数,这个函数从列表中删除已删除的记录

导出默认类PostList扩展组件 这一点。状态= { postList:( { id: 1、 名称:“所有项目”, },{ id: 2 名称:“库存物品”, } ), } remove_post_on_list = (deletePostId) => { this.setState ({ postList: this.state.postList。过滤(item => item。= deletePostId) }) } }

简单的解决方案使用切片而不改变状态

const [items, setItems] = useState(data);
const removeItem = (index) => {
  setItems([
             ...items.slice(0, index),
             ...items.slice(index + 1)
           ]);
}

非常简单 首先定义一个值

state = {
  checked_Array: []
}

Now,

fun(index) {
  var checked = this.state.checked_Array;
  var values = checked.indexOf(index)
  checked.splice(values, 1);
  this.setState({checked_Array: checked});
  console.log(this.state.checked_Array)
}

要从数组中删除一个元素,只需执行以下操作:

array.splice(index, 1);

在你的情况下:

removePeople(e) {
  var array = [...this.state.people]; // make a separate copy of the array
  var index = array.indexOf(e.target.value)
  if (index !== -1) {
    array.splice(index, 1);
    this.setState({people: array});
  }
},

只需过滤掉已删除的项,并再次用剩余的项更新状态,

let remainingItems = allItems.filter((item) => {return item.id !== item_id});
    
setItems(remainingItems);