在反应中从状态数组中删除项目

时间:2016-03-31 07:17:37

标签: javascript arrays reactjs

故事是,我应该能把Bob,Sally和Jack放进盒子里。我也可以从包装盒中取出。删除后,不会留下任何插槽。

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

我现在需要删除“鲍勃”。新数组将是:

["Sally", "Jack"]

这是我的反应组件:

...

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()在调用时不起作用。有任何想法吗?我是looking at this但是因为我正在使用React,我可能做错了。

14 个答案:

答案 0 :(得分:105)

使用React时,不应直接改变状态。如果更改了对象(或Array,也是对象),则应创建新副本。

其他人建议使用Array.prototype.splice(),但该方法会改变数组,因此最好不要将splice()与React一起使用。

最容易使用Array.prototype.filter()来创建新数组:

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

答案 1 :(得分:87)

要从数组中删除元素,只需执行:

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

答案 2 :(得分:23)

这是Aleksandr Petrov使用ES6的回应的一个小变化

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

答案 3 :(得分:7)

使用.splice从数组中删除项目。使用delete,不会更改数组的索引,但特定索引的值将为undefined

  

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

语法: array.splice(start, deleteCount[, item1[, item2[, ...]]])



var people = ["Bob", "Sally", "Jack"]
var toRemove = 'Bob';
var index = people.indexOf(toRemove);
if (index > -1) { //Make sure item is present in the array, without if condition, -n indexes will be considered from the end of the array.
  people.splice(index, 1);
}
console.log(people);




答案 4 :(得分:3)

filter 方法是在不触及状态的情况下修改数组的最佳方式。

它根据条件返回一个新数组。

在您的情况下,过滤器检查条件 person.id !== id 并根据条件创建一个不包括项目的新数组。

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

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

   setPeople( newPeople);
 };

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

不建议: 但是,如果您没有任何 id,您也可以为条件使用项目索引。

index !== itemIndex

答案 5 :(得分:0)

您忘记使用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
  })
},

但最好使用filter,因为它不会改变数组。 例如:

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

答案 6 :(得分:0)

提到了一些使用“拼接”的答案,正如史密斯·史密斯(Chance Smith)所说的那样,对阵列进行了突变。我建议您使用方法调用“切片” (Document for 'slice' is here)复制原始数组。

答案 7 :(得分:0)

这非常简单  首先,您定义一个值

state = {
  checked_Array: []
}

现在

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

答案 8 :(得分:0)

remove_post_on_list = (deletePostId) => {
    this.setState({
      postList: this.state.postList.filter(item => item.post_id != deletePostId)
    })
  }

答案 9 :(得分:0)

我也有同样的要求,从处于状态的数组中删除一个元素。

const array= [...this.state.selectedOption]
const found= array.findIndex(x=>x.index===k)
if(found !== -1){
   this.setState({
   selectedOption:array.filter(x => x.index !== k)
    })
 }

首先,我将元素复制到数组中。然后检查元素是否存在于数组中。然后只有我使用过滤器选项从状态中删除了该元素。

答案 10 :(得分:0)

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

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

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

答案 11 :(得分:0)

这里几乎所有的答案似乎都是针对类组件的,这里有一段代码在功能组件中对我有用。

const [arr,setArr]=useState([]);
const removeElement=(id)=>{
    var index = arr.indexOf(id)
    if(index!==-1){
      setArr(oldArray=>oldArray.splice(index, 1));
    }
}

答案 12 :(得分:-1)

   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了解更多信息

答案 13 :(得分:-1)

const array = [...this.state.people];
array.splice(i, 1);
this.setState({people: array});         
相关问题