【问题标题】:Error: "Too many re-renders. React limits the number of renders to prevent an infinite loop"错误:“重新渲染过多。React 限制渲染次数以防止无限循环”
【发布时间】:2021-09-05 07:29:01
【问题描述】:

如何防止这个错误?

错误:重新渲染过多。 React 限制渲染次数以防止无限循环
我的代码

import React, { useState, useEffect, useRef } from "react";

const Dropdown = ({ options, selected, onSelectedChange }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef();

  useEffect(() => {
    const onBodyClick = (event) => {
      if (ref.current.contains(event.target)) {
        return;
      }
      setOpen(false);
    };
    document.body.addEventListener("click", onBodyClick, { capture: true });

    return () => {
      document.body.removeEventListener("click", onBodyClick, {
        capture: true,
      });
    };
  }, []);



我相信导致它重新渲染的唯一原因是 useEffect 我试图删除它并再次运行应用程序并出现同样的错误!

【问题讨论】:

  • i tried to delete it and run the app again and the same error! 听起来错误是由另一段代码引起的。您显示的代码对我来说看起来不错。
  • 这是应用组件代码:``` const App = () => { const [selected, setSelected] = useState(options[0]);常量 [dropDown, setdropDown] = useState(true);返回 (
    {dropDown ? ( ) : null}
    ); };导出默认应用程序; ```

标签: reactjs


【解决方案1】:

我看到问题是你在渲染组件时调用setdropDown。所以会出现这个错误。您只需像这样更新:

<button onClick={() => setdropDown(!dropDown)}>

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2021-12-25
    • 2021-07-01
    • 2021-05-17
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多