简体   繁体   English

从 state 中删除特定项目

[英]Removing a specific item from state

I want to remove just one array item from state on click but im having troubles getting this to work.我想在点击时从 state 中删除一个数组项,但我无法让它工作。 My state looks like this below, and i want to remove one of the datasets on click (for example label 2).我的 state 如下所示,我想在单击时删除其中一个数据集(例如 label 2)。

state = {
  data: {
    labels: time,
    datasets:[
      {
       "label": "Label 1",
      },
      {
       "label": "Label 2",
      },
      {
       "label": "Label 3",
      },
    ] 
  }
}

The actual dataset is A LOT larger and I would usually just redefine the state using setState, but this isnt practical because of the huge data.实际的数据集要大很多,我通常会使用 setState 重新定义 state,但这并不实用,因为数据量很大。 Is there a way I can just remove this one array item?有没有办法我可以删除这个数组项? I've tried creating a function to remove the item as suggested on another post but i can only get it to work for top level keys.我已经尝试创建一个 function 来删除另一篇文章中建议的项目,但我只能让它适用于顶级密钥。

removekey = (keyname) => {
        let newState = this.state;
        delete newState[keyname];
        this.setState(newState)
}

this.removekey('data.datasets[1]');

A couple things:几件事:

When you declare newState , you're not actually preventing direct state mutation because simply declaring a new variable creates a reference to the state object, not an entirely new one.当您声明newState时,您实际上并没有阻止直接 state 突变,因为简单地声明一个新变量会创建对 state object 的引用,而不是一个全新的变量。 Try Array.from(this.state.datasets) .尝试Array.from(this.state.datasets)

You can then set that new array as a replacement for the datasets array in your state: this.setState({ datasets: newData }) .然后,您可以将该新数组设置为 state: this.setState({ datasets: newData })中的datasets数组的替换。

If you want to write a function to do this dynamically, I would write one that takes an index and edits the data array directly:如果你想写一个 function 来动态地做到这一点,我会写一个带索引并直接编辑数据数组的:

removeItem = (index) => {
        let newData = Array.from(this.state.datasets);
        newData.splice(index, 1);
        this.setState({ datasets: newData })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM