【发布时间】:2023-03-19 05:14:01
【问题描述】:
我正在尝试编写一个切换子元素的 onClick 方法,但我当前的实现导致以下错误:
Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
我不确定需要如何更改我的设置才能不导致此无限循环。以下是我的容器组件的设置方式:
import React, { Component } from 'react';
import styled from 'styled-components';
const NestedProperty = styled.div`
margin-left: 2rem;
`;
const ParentContainer = styled.div`
display: flex;
flex-direction: column;
`;
const NestedContainer = styled.div`
display: flex;
flex-direction: column;
`;
class SideMenuContainer extends Component {
constructor(props, context) {
super(props, context);
this.state = {
active: false
};
}
handleClick(){
console.log("toggle click!")
this.setState({active : !this.state.active});
}
render() {
if (this.state.active == true){
return (
<ParentContainer>
<p onClick={this.handleClick()}>{this.props.parentName}</p>
<NestedContainer>
{this.props.properties.map(propertyElement => {
return (
<NestedProperty onClick={() => { this.props.changeInfoList(propertyElement.name, propertyElement.data_type, propertyElement.app_keys.join(', '))}} >
{propertyElement.name}
</NestedProperty>
);
})}
</NestedContainer>
</ParentContainer>
);
}
else {
return (
<ParentContainer>
<p onClick={this.handleClick()}>{this.props.parentName}</p>
</ParentContainer>
);
}
}
}
export default SideMenuContainer;
本质上,我想要做的是拥有它,以便每当单击parentName 时,它的子 (NestedProperty) div 就会打开和关闭。如果state中的active属性为true,则子NestedProperty div在Parent下渲染,如果其false,则只渲染parentName。
是什么导致了这个无限循环?
【问题讨论】:
标签: reactjs