首页 > 解决方案 > onClick 方法连续多次运行 setState,否定预期目的

问题描述

我试图让我的 onClick 方法handleClick设置activegroupCardInfo属性的状态。active特别是一个布尔值,我使用这个布尔值来确定是否应该扩展侧边菜单项。

SideMenuContainer组件调用handleClick

render() {
    if (this.props.active == true){
      return (
        <ParentContainer>
          <p onClick={this.props.handleClick(this.props.properties)}>{this.props.parentName}</p>        
          <NestedContainer>
            {this.props.properties.map(propertyElement => {
              return (
                <NestedProperty onClick={() => { this.props.changeInfoList(propertyElement.name, propertyElement.data_type, propertyElement.app_keys)}} >
                  {propertyElement.name}
                </NestedProperty>
              );
            })}
          </NestedContainer>
        </ParentContainer>
      );    
    }

问题是单击会<p>导致handleClick多次运行。因此,它不是将active值从 false 切换到 true,而是多次来回切换,以便再次从 false 回到 false。

我在App.js导致此问题的父级中构造此方法的方式有什么不正确的地方?:

  handleClick(properties){
    console.log("toggle click!")
    // this.setState({active : !this.state.active});

    this.setState({
      active: !this.state.active,
      groupedCardInfo: properties
    })

    console.log("the active state is now set to: " + this.state.active)
  }

标签: reactjs

解决方案


这是因为您正在事件处理程序中调用该函数。第一次render运行它将执行您的事件处理程序。您可以像其他onClick处理程序一样执行此操作:

<p onClick={() => { this.props.handleClick(this.props.properties) }}>{this.props.parentName}</p>

或者你可以这样做:

<p onClick={this.props.handleClick}>{this.props.parentName}</p>

但是,您将不得不更改properties在单击处理程序中引用的方式。像这样:

handleClick(){
    const properties = this.props.properties

    this.setState({
      active: !this.state.active,
      groupedCardInfo: properties
    })

    console.log("the active state is now set to: " + this.state.active)
  }

推荐阅读