【问题标题】:React component toggle method causing `Uncaught Invariant Violation: Maximum update depth exceeded.` error反应组件切换方法导致“未捕获的不变违规:超出最大更新深度。”错误
【发布时间】: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


    【解决方案1】:

    您错误地传递了函数handleClick。改成

    onClick={this.handleClick}
    

    你需要绑定函数,你可以用粗箭头符号来做到这一点

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

    【讨论】:

    • 啊,我明白了。进行这些更改后,页面渲染成功,但单击不会执行任何操作,并且控制台会发出警告说“警告:在现有状态转换期间无法更新(例如在render 内)。渲染方法应该是纯粹的道具和状态的功能。”
    【解决方案2】:

    您的函数未与“this”正确绑定。像下面这样使用它

        onClick = { () => this.handleClick() }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2020-06-14
      • 2022-06-14
      • 2020-08-11
      相关资源
      最近更新 更多