我如何 console.log 在 React 中更改状态?

How do I console.log a changed state in React?

我是 React 的新手,正在研究别人的代码(陷入困境)。

有一个简单的按钮有一个 handleClick() 处理程序。我想将特定状态递增 1。

为此我已经尝试过:

state = {
  page: 0,
}

  handleClick() {

    this.setState(state => ({
      page: state.page + 1
    }))

    console.log(page)
  }

但这只会产生 page is not defined 错误。

我尝试了上述的各种组合,例如 console.log(state.page)page: page + 1 等,但没有得到任何结果。

有人知道我如何通过控制台日志来测试状态是否正在更新吗?

只需向您 this.setState 传递一个回调函数,它将在状态更新后调用。如下所示:

this.setState(state => ({
      page: state.page + 1
    }), () => console.log(this.state) )

样本sandbox

您不能直接引用页面。您必须使用 this.state 引用。尝试:

  handleClick() {
    this.setState(state => ({
      page: state.page + 1
    }))
    console.log(this.state.page)
  }
React 中的

setState 是一种异步方法,因此当您尝试在更新后立即控制更新后的状态时,console.log 只会为您提供之前的状态。因此,为了应对,您需要在 setState 的回调函数中控制状态,如下所示:

handleClick() {

    this.setState({
      page: this.state.page + 1
    }, () => {
       console.log(this.state.page)
    })
}

现在 console.log 将为您提供更新后的状态。

您应该使用回调来查看更改后的状态,因为 setState 在 React 中是异步的。根据文档:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

 handleClick = () => {
    this.setState({ page: this.state.page + 1 }, () => {
    console.log(this.state.page)
    })
 }