ReactJS onClick状态改变了一步 [英] ReactJS onClick state change one step behind

查看:47
本文介绍了ReactJS onClick状态改变了一步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ReactJS构建一个非常原始的测验应用程序,但我无法更新 Questions 组件的状态。它的行为是它将问题数组的正确索引呈现给DOM,尽管 this.state.questionNumber 总是一个后退在 handleContinue()

I'm building a very primitive quiz app with ReactJS and I'm having trouble updating the state of my Questions component. Its behavior is it renders the correct index of the questions array to the DOM despite this.state.questionNumber always being one step behind in handleContinue():

import React from "react"

export default class Questions extends React.Component {
  constructor() {
    super()
    this.state = {
      questionNumber: 1
    }
  }

  //when Continue button is clicked
  handleContinue() {
    if (this.state.questionNumber > 3) {
      this.props.unMount()
    } else {
      this.setState({
        questionNumber: this.state.questionNumber + 1
      })
      this.props.changeHeader("Question " + this.state.questionNumber)
    }
  }

  render() {
    const questions = ["blargh?", "blah blah blah?", "how many dogs?"]
    return (
      <div class="container-fluid text-center">
        <h1>{questions[this.state.questionNumber - 1]}</h1>
        <button type="button" class="btn btn-primary" onClick={this.handleContinue.bind(this)}>Continue</button>
      </div>
    )
  }
}


推荐答案

setState()不一定是同步操作


setState()不会立即改变 this.state ,但会创建挂起状态转换。访问 this.state aft

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state aft

无法保证对 setState的调用同步操作并且可以批量调用以获得性能提升。

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

因此,这个.state.questionNumber 可能仍然保留此前的值:

For this reason, this.state.questionNumber may still hold the previous value here:

this.props.changeHeader("Question " + this.state.questionNumber)






使用一旦调用的回调函数状态转换已完成


Instead, use the callback function that is called once the state transition is complete:

this.setState({
    questionNumber: this.state.questionNumber + 1
}, () => {
    this.props.changeHeader("Question " + this.state.questionNumber)
})

这篇关于ReactJS onClick状态改变了一步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆