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

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。


当前回答

const [people, setPeople] = useState(data);

const handleRemove = (id) => {
   const newPeople = people.filter((person) => { person.id !== id;
     setPeople( newPeople );
     
   });
 };

<button onClick={() => handleRemove(id)}>Remove</button>

其他回答

使用.splice从数组中删除项。使用delete,数组的索引不会被改变,但特定索引的值将是未定义的

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。

语法:数组。splice(start, deleteCount[, item1[, item2[,…]]])

var people = ["Bob", "Sally", "Jack"] var toRemove = 'Bob'; var index = people.indexOf(toRemove); if (index > -1){//确保item存在于数组中,如果没有if条件,-n个索引将被考虑从数组的末尾开始。 人。拼接(指数(1); } console.log(人);

编辑:

正如justin-grant指出的,作为经验法则,永远不要改变这个。直接调用setState(),因为之后调用setState()可能会替换您所做的突变。对待这个问题。状态,仿佛它是不可变的。

另一种方法是,在其中创建对象的副本。状态和操作副本,使用setState()将它们赋值回去。数组#映射,数组#过滤器等可以使用。

this.setState({people: this.state.people.filter(item => item !== e.target.value);});

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

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

这是你当前的状态变量

const [animals, setAnimals] = useState(["dogs", "cats", ...])

调用此函数并传递要删除的项。

removeItem("dogs")

const removeItem = (item) => {
    setAnimals((prevState) =>
      prevState.filter((prevItem) => prevItem !== item)
    );
  };

你的状态函数现在变成:

["cats", ...]

另一种方法是使用useState钩子。检查文档:https://reactjs.org/docs/hooks-reference.html#functional-updates它声明:与类组件中的setState方法不同,useState不会自动合并更新对象。您可以通过将函数更新器表单与对象扩展语法组合来复制此行为,如下所示,或者使用useReducer钩子。

const [state, setState] = useState({});
setState(prevState => {
  return {...prevState, ...updatedValues};
});

删除具有特定值的元素 // 注意过滤器函数总是返回一个新数组。

const people = ["Bob", "Sally", "Jack"]
    
const removeEntry = (remove) => {
const upDatePeople = people.filter((Person) =>{
return Person !== remove
});
console.log(upDatePeople)
//Output: [ 'Sally', 'Jack' ]
}
removeEntry("Bob");

非常简单 首先定义一个值

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