Home > database >  Error: Max update depth exceeded. This can happen when a component repeatedly calls setState inside
Error: Max update depth exceeded. This can happen when a component repeatedly calls setState inside

Time:03-22

I want to do in class component what I did in function component, but it gives an error. How can I fix?

function component:

const [listBtnClassName, setListBtnClassName] = useState("listBtnPulse");

useEffect(() => {
    if (showGrid) {
      setListBtnClassName("listBtnPulseNone");
    }
  }, [showGrid]);

<PageFilter listBtnClassName={listBtnClassName} ></PageFilter>

class component:

this.state = {
      listBtnClassName: "listBtnPulse",
    };

 componentDidUpdate() {
    if (this.props.showGrid) {
      this.setState({ listBtnClassName: "listBtnPulseNone" });
    }
  }

<PageFilter listBtnClassName={this.state.listBtnClassName} ></PageFilter>

Error: 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.

CodePudding user response:

You need to make sure the showGrid from the previous props is not true, but the showGrid from current props is true.

See this document for more information.

this.state = {
  listBtnClassName: "listBtnPulse",
};

componentDidUpdate(prevProps) {
  if (!prevProps.showGrid && this.props.showGrid) {
    this.setState({ listBtnClassName: "listBtnPulseNone" });
  }
}
<PageFilter listBtnClassName={this.state.listBtnClassName} ></PageFilter>

  • Related