【问题标题】:How to update most current state in class component如何更新类组件中的最新状态
【发布时间】:2021-05-13 09:05:01
【问题描述】:

我有一个带有cursorIndex 的组件,我一直在将它从功能组件重构为类组件。

当它是一个函数式组件时,我正在使用useState 状态挂钩,我可以将一个函数传递给useState,它会更新最新的cursorIndex。例如:

// cursorIndex => 1

setCursorIndex(currentIndex => currentIndex + 1)
setCursorIndex(currentIndex => currentIndex + 1)

// cursorIndex => 3

// Even though the update is asynchronous, somehow React
// applies both of these increments and not just one. Great!

现在我有一个类组件。我编写了自己的 setter 函数,以便将其传递给孩子:

setCursorIndex(incrementor){
  this.setState({ 
    cursorIndex: incrementor(this.state.cursorIndex)
  })
}

除了它通过的状态不一定是最新状态之外,它工作正常。

// cursorIndex => 1

setCursorIndex(currentIndex => currentIndex + 1)
setCursorIndex(currentIndex => currentIndex + 1)

// cursorIndex => 2

我希望将组件保留为类组件,因为我希望能够轻松地将其所有状态重置为默认值。有没有办法让它像 useState 那样更新当前状态?或者,我应该将其保留为功能组件吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在文档中很清楚:

    
    incrementCount() {
      this.setState((state) => {
        // Important: read `state` instead of `this.state` when updating.
        return {count: state.count + 1}
      });
    }
    

    https://reactjs.org/docs/faq-state.html

    好吧,尽管我觉得自己很愚蠢,但我想我还是把它留在这里,以防它帮助别人。

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2022-07-19
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多