在有状态组件中切换布尔值

时间:2018-06-13 18:57:06

标签: javascript reactjs

我有一个相当简单的有状态组件,只要有人点击按钮,我就希望切换它的值:

class Layout extends Component {
  state = {
    sidedrawer: false
  }

  sideDrawerCloseHandler = () => {
    this.setState({sidedrawer: false})
  }

  sideDrawerTogglerHandler = () => {
    this.setState({sidedrawer: !sidedrawer})
  }

  render () {
    return (
      <Aux>
        <Toolbar sideDrawerTogglerHandler={this.sideDrawerTogglerHandler}/>
        <SideDrawer SideDrawerOpen={this.state.sidedrawer} sideDrawerCloseHandler={this.sideDrawerCloseHandler} />
        <main className={classes.co}>
          {this.props.children}
        </main>
      </Aux>
    )
  }
}

export default Layout;

现在,当我运行我的反应应用程序时,它会抛出错误说:

  

sidedrawer未在第19行中定义

有人可以帮我修复和理解错误吗?

第18-19行恰好是我代码中的这一部分

sideDrawerTogglerHandler = () => {
  this.setState({sidedrawer: !sidedrawer})
}

2 个答案:

答案 0 :(得分:3)

你必须从你的州获得sidedrawer

sideDrawerTogglerHandler = () => {
 this.setState((previousState) => {
   return {sidedrawer: !previousState.sidedrawer}
 })
}

答案 1 :(得分:2)

侧抽屉未定义,定义的是this.state.sidedrawer,您正在寻找的是

      sideDrawerTogglerHandler = () => {
           this.setState({sidedrawer: !this.state.sidedrawer})
      }

但这不是setState的最佳方式,正如React docs所解释的那样,基于先前状态更新状态的最佳方法是使用带有接收prevState作为prop的函数的setState,你可以试试而不是

 sideDrawerTogglerHandler = () => {
     this.setState((prevState) => ({
      sidedrawer: !prevState.sidedrawer 
    }));
   }