[英]Why is my splice deleting all but the first instead of only the one specified?
For a given array, when I run the splice everything but the first entry is deleted.对于给定的数组,当我运行拼接时,除了第一个条目之外的所有内容都被删除。 However I would expect only the selected entry to be deleted.但是,我希望只删除选定的条目。 I suspect this has something to do with how my i is set up but I'm not sure what the problem is.我怀疑这与我的 i 设置方式有关,但我不确定问题是什么。
removethisone = (i) => {this.setState(state=>({list: state.list.splice(i,1)}))}
<ul>
{this.state.list.map((entry, i)=><li key={i}><button onClick={this.removethisone}>{i+1}</button>{entry}</li>)}
</ul>
Your code is working exactly as you described because that is how splice works .您的代码完全按照您的描述工作,因为这就是splice 的工作方式。
The splice method returns an array of the items that are removed. splice 方法返回一个包含被删除项目的数组。 You are storing the items you removed back into the state.您正在将移除的项目存储回状态。 Hence why you get what you removed.因此,为什么你会得到你删除的东西。
removethisone = (i) => {
this.setState(state => {
const list = state.list;
const removedElems = list.splice(i, 1);
console.log(removedElems);
return {
list
}
})
}
The reason this is happening is because the Array.splice
method returns the removed items from the array.发生这种情况的原因是Array.splice
方法返回从数组中删除的项目。
You need to do something like this:你需要做这样的事情:
removethisone = (i) => {
this.setState(state => {
const nextState = [ ...state.list ]
nextState.splice(i, 1)
return { list: nextList }
})
}
For example, run the code below to see the ouput:例如,运行下面的代码以查看输出:
// This is what your code does let numbers = [1, 2, 3, 4, 5]; let removedNumbers = numbers.splice(2, 1) numbers = removedNumbers console.log(numbers); console.log(removedNumbers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.