【问题标题】:Error: setState(...): takes an object of state variables to update or a function which returns an object of state variables错误:setState(...):需要一个状态变量对象来更新或一个返回状态变量对象的函数
【发布时间】:2020-02-03 06:30:33
【问题描述】:

这在 this.state.incorrect + 1this.state.correct + 1 的其他部分给了我错误

我看到了这个但没有解决我的问题React Native: setState(...): takes an object of state variables to update or a function which returns an object of state variables

if (choice == this.state.dataset[this.state.current].correct) {
            this.setState(this.state.correct + 1)
        } else {
            this.setState(this.state.incorrect + 1)
        }

【问题讨论】:

  • 我认为你需要发送一个带有键和值的对象到 setState
  • 请发布更多代码以更好地理解问题。
  • @AnkitaKuchhadiya DILEEPTHOMAS 解决了我的问题,谢谢!
  • @shivlalkumavat 我还详细发布了答案,以获取更多知识。

标签: javascript reactjs react-redux react-router


【解决方案1】:

在反应中,setState 接受一个对象或一个异步函数。你没有使用它们。在你的情况下,如果你需要更新你需要使用的状态值

this.setState({correct: this.state.correct + 1});

在使用这种设置状态值的方式时也要小心,因为setState 是异步操作,您可能无法保证立即获取状态变量的值。如果您想使用setState() 的值,请使用带有setState 的异步回调

  this.setState({correct: this.state.correct + 1}, function() {
     // you get the new value of state immediately at this callback
  });

【讨论】:

  • 好的,我知道了,谢谢!
  • @shivlalkumavat 乐于助人
【解决方案2】:

您需要更新状态,因为您定义的状态是一个对象。并且您需要告知您正在更新的对象的哪个属性,如下所示。

if (choice == this.state.dataset[this.state.current].correct) {
            this.setState({correct: this.state.correct + 1})
        } else {
            this.setState({incorrect: this.state.incorrect + 1})
        }

文档ref

更新

由于 @titus 在 cmets 上的正确更新方式如下所示,因为 react 给出了 prevState 对象,该对象具有组件的 prev 状态。

this.setState(prevState => ({correct: prevState.correct + 1}))

【讨论】:

  • 当新状态是从前一个状态派生出来的,你应该使用setState作为第一个参数,例如:this.setState(prevState => ({correct: prevState.correct + 1}))
  • 由于状态没有更新@Titus,使用 prevState.correct 和 this.state.correct 有什么区别
  • @shivlalkumavat 很乐意为您提供帮助,如果对您有用,请接受 :)
  • HERE有解释
  • 所以目前 setState 可以是异步的,而同步不是因为当我们在承诺级别内设置状态时,它将是同步的,而在正常的事件处理程序中,它将是异步的,所以这将被改变我的反应17 通过使用并发模式,这是正确的@Titus
猜你喜欢
  • 2019-05-31
  • 2020-02-12
  • 2020-05-02
  • 1970-01-01
  • 2019-12-22
  • 2023-02-15
  • 1970-01-01
  • 2019-03-22
  • 2021-02-03
相关资源
最近更新 更多