如何在反应中使用setState来更新数组?

时间:2018-06-08 15:04:41

标签: javascript arrays reactjs ecmascript-6

我需要在React中更新我的组件状态中的数组。 我已经通过这个问题找到了几个主题,但到目前为止所有这些都是使用spread运算符向数组中添加新项目,但我需要在回调中添加或删除项目,如下所示:

  handleCheck (newStatus, isChecked) {
    this.setState({ filterStatus: [...this.state.filterStatus, newStatus] })
  }

但是这里的问题是它不能用于isChecked布尔值为false的状态,以便从数组中删除它们

添加或删除该数组中的项目的最佳方法是什么,希望使用扩展运算符?

由于

3 个答案:

答案 0 :(得分:4)

尝试使用.filter删除元素。在使用.filter之前,请记住复制数组(使用[...array]语法),不要更改原始数组:

handleCheck (newStatus, isChecked) {
    let newArray = isChecked? // if isChecked is true
        [...this.state.filterStatus, newStatus] : // add element
        [...this.state.filterStatus].filter(e => e !== newStatus); // remove the elements that are equal to newStatus
    this.setState({ filterStatus: newArray})
}

答案 1 :(得分:0)

检查,仅在bool isChecked为true时添加元素,否则使用filter从数组中删除元素。

像这样:

handleCheck (newStatus, isChecked) {
    this.setState(prevState => { 
        let filterStatus;
        if (isChecked) {
            filterStatus = [...prevState.filterStatus, newStatus];
        } else {
            filterStatus = prevState.filterStatus.filter(el => el.id !== newStatus.id)
        }
        return { filterStatus }
    })
}

注意:在过滤器回调方法中使用正确的唯一属性名称代替id。

答案 2 :(得分:0)

认为它是功能性的!

this.$router.currentRoute