onClick方法连续多次运行setState,否定了预期目的

问题描述 投票:0回答:2

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

调用handleClick的SideMenuContainer组件:

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
2个回答
1
投票

这是因为你在事件处理程序中调用该函数。 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)
  }

1
投票

尝试使用箭头功能,就像你在其他onClick上所做的那样:

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

在渲染时调用this.props.handleClick...,调用它。然后,设置状态,使组件重新渲染。

© www.soinside.com 2019 - 2024. All rights reserved.