无法在React Native中更新数组

时间:2019-02-11 20:18:21

标签: javascript reactjs react-native jsx

我正在尝试更改数组中项目的状态。我做了您对上一个答案的评论,但是当我console.log我正在更新的数组时,它的数量在增加!这是代码

changeState = (i) => {
  console.log(this.state.selected)
  const array = [...this.state.selected];

  if (this.state.selected[i] === true) {
    array[i] = false
  } else {
    array[i] = true
  }

  this.setState({
    selected: array
  })

  console.log(array[i])
}

运行屏幕时,我创建的选定数组的所有值都为false,然后按下按钮时,它将使用“ i”发送索引,然后使用该数组发送而不是从true更改为false,反之亦然,仅发送数组尺寸增加

2 个答案:

答案 0 :(得分:0)

这是您的阵列的克隆。您无法更新其值。

const array = [...this.state.selected];

答案 1 :(得分:0)

代码看起来还可以。请注意,在JavaScript中,您可以在一个未定义的索引中分配一个当前超出数组范围的值。 例如:

var arr=[];
arr[2]="value";
// arr = [undefined,undefined,"value"];
// arr.length = 3

所以我唯一能想到的是changeState的索引错误(可能是比您所在状态的数组大的索引)