React state does not update updates

when tab is switched, the currently selected tab,debugger is updated and found that state has not been updated. What is the specific reason? thank you very much!

constructor(props) {
    super(props)
    this.state = {
      selected: "blacklist"
    }
  }
tabChange(newSelected) {  // newSelected = "score"
    const {selected} = this.state; // selected = "blacklist"
    debugger
    if (selected !== newSelected) { // selected = "blacklist", newSelected = "score"
      this.setState({
        selected: newSelected,
      })
      const {tabChange} = this.props
      tabChange(newSelected)
    }
    debugger
    const state = this.state //state = {selected: "blacklist",}
    console.log(state)
  }
May.11,2021

setState is asynchronous. You need to go back in the callback to get the updated state.

  

react's setState in the lifecycle and event handler is merged (asynchronously). (all will mutate after version 17)

Menu