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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36326612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:55:52  来源:igfitidea点击:

Delete item from state array in react

javascriptarraysreactjs

提问by Sylar

The story is, I should be able to put Bob, Sally and Hyman into a box. I can also remove either from the box. When removed, no slot is left.

故事是,我应该能够把鲍勃、莎莉和Hyman放进一个盒子里。我也可以从盒子中取出。移除后,没有留下任何插槽。

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

I now need to remove, say, "Bob". The new array would be:

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

["Sally", "Hyman"]

Here is my react component:

这是我的反应组件:

...

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

...

Here I show you a minimal code as there is more to it (onClick etc). The key part is to delete, remove, destroy "Bob" from the array but removePeople()is not working when called. Any ideas? I was looking at thisbut I might be doing something wrong since I'm using React.

在这里,我向您展示了一个最少的代码,因为它还有更多内容(onClick 等)。关键部分是从数组中删除、移除、销毁“Bob”,但removePeople()在调用时不起作用。有任何想法吗?我正在看这个,但由于我使用的是 React,我可能做错了什么。

回答by iaretiga

When using React, you should never mutate the state directly. If an object (or Array, which is an object too) is changed, you should create a new copy.

使用 React 时,永远不要直接改变状态。如果一个对象(或者Array,它也是一个对象)被改变了,你应该创建一个新的副本。

Others have suggested using Array.prototype.splice(), but that method mutates the Array, so it's better not to use splice()with React.

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

Easiest to use Array.prototype.filter()to create a new array:

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

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

回答by MarcoS

To remove an element from an array, just do:

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

array.splice(index, 1);

In your case:

在你的情况下:

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

回答by Dmitry

Here is a minor variation on Aleksandr Petrov's response using ES6

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

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

回答by Rayon

Use .spliceto remove item from array. Using delete, indexes of the array will not be altered but the value of specific index will be undefined

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

The splice()method changes the content of an array by removing existing elements and/or adding new elements.

拼接()方法改变阵列的通过去除现有元件和/或添加新元素的内容。

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

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

var people = ["Bob", "Sally", "Hyman"]
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);

Edit:

编辑:

As pointed out by justin-grant, As a rule of thumb, Nevermutate this.statedirectly, as calling setState()afterward may replace the mutation you made. Treat this.stateas if it were immutable.

正如justin-grant所指出的那样,根据经验,永远不要this.state直接变异,因为setState()之后调用可能会替换您所做的变异。将其this.state视为不可变的。

The alternative is, create copies of the objects in this.stateand manipulate the copies, assigning them back using setState(). Array#map, Array#filteretc. could be used.

另一种方法是,创建对象this.state的副本并操作副本,使用setState(). Array#mapArray#filter等等,也可以被使用。

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

回答by ANKIT-DETROJA

Easy Way To Delete Item From state array in react:

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

when any data delete from database and update list without API calling that time you pass deleted id to this function and this function remove deleted recored from list

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

export default class PostList extends Component {
  this.state = {
      postList: [
        {
          id: 1,
          name: 'All Items',
        }, {
          id: 2,
          name: 'In Stock Items',
        }
      ],
    }


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

回答by Arthur Chen

Some answers mentioned using 'splice', which did as Chance Smith said mutated the array. I would suggest you to use the Method call 'slice' (Document for 'slice' is here)which make a copy of the original array.

一些答案提到使用“拼接”,正如 Chance Smith 所说的那样改变了数组。我建议你使用 Method call 'slice' 'slice' 的 文档在这里),它可以复制原始数组。

回答by QC innodel

It's Very Simple First You Define a value

首先定义一个值非常简单

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

回答by Aleksandr Petrov

You forgot to use setState. Example:

你忘了使用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
  })
},

But it's better to use filterbecause it does not mutate array. Example:

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

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

回答by Gibbs

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 docfor more info

Redfer文档了解更多信息