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

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 [randomNumbers, setRandomNumbers] = useState([111,432,321]);
const numberToBeDeleted = 432;

// Filter (preferred)
let newRandomNumbers = randomNumbers.filter(number => number !== numberToBeDeleted)
setRandomNumbers(newRandomNumbers);

//Splice (alternative)
let indexOfNumberToBeDeleted = randomNumbers.indexOf(numberToBeDeleted);
let newRandomNumbers = Array.from(randomNumbers);
newRandomNumbers.splice(indexOfNumberToBeDeleted, 1);
setRandomNumbers(newRandomNumbers);


//Slice (not preferred - code complexity)
let indexOfNumberToBeDeleted = randomNumbers.indexOf(numberToBeDeleted);
let deletedNumber = randomNumbers.slice(indexOfNumberToBeDeleted, indexOfNumberToBeDeleted+1);
let newRandomNumbers = [];
for(let number of randomNumbers) {
    if(deletedNumber[0] !== number)
        newRandomNumbers.push(number);
};
setRandomNumbers(newRandomNumbers);

其他回答

你忘记使用setState。例子:

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

但最好使用过滤器,因为它不会改变数组。 例子:

removePeople(e){
  var array = this.state.people.filter(function(item) {
    return item !== e.target.value
  });
  this.setState({
    people: array
  })
},

非常简单 首先定义一个值

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)
}
const [people, setPeople] = useState(data);

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

<button onClick={() => handleRemove(id)}>Remove</button>
removePeople(e){
    var array = this.state.people;
    var index = array.indexOf(e.target.value); // Let's say it's Bob.
    array.splice(index,1);
}

Redfer doc获取更多信息

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

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