【问题标题】:React: mutating state with ++React:用 ++ 改变状态
【发布时间】:2018-10-30 13:09:09
【问题描述】:

在使用带有“++”的 SetState(例如,this.state.counter++)时,我不断收到“不要变异”警告,而当我使用“+1”设置它时却没有得到它。为什么会这样?

【问题讨论】:

  • 只能使用setState 改变状态。由于您正在尝试设置状态,因此您可以使用变量赋值来获取先前的值以对其进行修改:let {counter} = this.state; this.setState({ counter: counter++ }) 请记住,++ 只会在操作结束后增加值,如果您遇到其他增量错误
  • 我在使用 SetState 时遇到错误。
  • 那是因为你应该使用setState 而不是SetState。错误说明了什么?
  • @EternalDoubter 你能把你的示例代码贴在你得到这个警告的地方吗?

标签: reactjs


【解决方案1】:

this.state.counter++ 表达式递增 this.state.counter 并返回递增值。 this.state.counter + 1 表达式只返回递增的值。 为避免任何其他冲突,您不应根据this.state 设置新状态。请改用此代码:

this.setState(old => ({counter: old.counter + 1}))

查看https://reactjs.org/docs/react-component.html#setstate

【讨论】:

  • 谢谢。我收到了使用该语法的警告。
猜你喜欢
  • 2019-05-15
  • 1970-01-01
  • 2018-05-06
  • 2020-05-03
  • 2019-03-16
  • 2018-06-08
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多