reactjs - onClick 方法连续多次运行 setState,否定预期目的
问题描述
我试图让我的 onClick 方法handleClick
设置active
和groupCardInfo
属性的状态。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)
}
解决方案
这是因为您正在事件处理程序中调用该函数。第一次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)
}
推荐阅读
- amazon-web-services - 雪花故障转移 - 复制机制
- css - 带有固定阴影的 CSS 拖放动画
- java - Open JDK Like Memory Calculator 错误 Cloud Foundry
- javascript - 使用 HTML/CSS/JS 在 Rails 应用程序中过滤元素
- html - 在 Angular 中创建组件时,浏览器给我“formGroup 需要一个 FormGroup 实例。请传入一个”
- algorithm - 如何在 Haskell 中调试 BST 验证算法?
- android - 在 TextViews 中使用表情符号...它们会在 Android 版本之间发生变化吗?
- typescript - 如何从嵌套对象中获取类型
- interop - 如何将返回 void 的 java 函数传递给 kotlin 高阶函数
- firefox - 替换 Firefox 扩展 Firebug