如何使用setstate

时间:2019-07-08 12:56:39

标签: reactjs state mutate

这里是反应的初学者!

我有一个带有状态的组件,像这样:

this.state = {
  values: [],
  isloading: true,
  error: false,
  page: 1,
  next: null,
  score: 0,
  seconds: 120,
  finished: false,
  modalopened: false,
  currentcharacter: null,
};

我正在代码中间直接更改此组件的状态,如下所示:

this.state.values[index_value].points = 5

我得到警告,告诉我使用“ setState”。 但是如何使用values[index].points访问setState

提前感谢vm

3 个答案:

答案 0 :(得分:2)

我建议在开始编码之前先看一下React DOCS

无论如何,正确的方法:

let arr = [...this.state.values]; // it clones your array without references
arr[index_value].points = 5; // modify only cloned array
this.setState({ values: arr }, () => console.log(this.state)); // set the new array in place of the old one

答案 1 :(得分:2)

永远不要直接更改状态。

您应该使用setState的回调方式。

this.setState(prevState => {
    let newValues = [...prevState.values]
    newValues[index_value].points = 5
    return { values: newValues }
})

答案 2 :(得分:2)

建议更新状态的方法是通过setState方法,构造函数只是该规则的一个例外,我们可以在其中直接分配状态,例如:

this.state = {
  values: [],
  isloading: true,
  error: false,
  page: 1,
  next: null,
  score: 0,
  seconds: 120,
  finished: false,
  modalopened: false,
  currentcharacter: null,
};

此分配后,应始终使用setState函数更新状态,如果状态更新取决于状态的先前值,则应将先前状态传递给该函数,即将数字加1,更新true / false标志等