我有一个代码库,其中到处都是tempVar,就像下面的示例一样
const tempQuestions = this.state.questions
const result = tempQuestions.filter(function(value, index1) {
return index !== index1
})
this.setState({
questions: result
})
如何避免这种情况?
答案 0 :(得分:1)
编辑:
因为您知道要删除的索引值。正如@undefined所述,您可以使用Array.prototype.splice()
方法删除值,而不是遍历整个数组
检查以下解决方案,该解决方案将删除一个索引值
const { questions } = this.state;
const result = questions.slice();
result.splice(index, 1);
this.setState({
questions: result
})
答案 1 :(得分:1)
这看起来非常简单:
this.setState({
questions: this.state.questions.filter((q, i) => index !== i)
})
使用splice
首先需要克隆该数组,否则setState
不会通知状态更改。因此,无论哪种方式都需要迭代,因为filter
比splice
更有意义。