ReactJS, react-bootstrap, Modal Box: "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."

ReactJS, react-bootstrap, Modal Box: "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."

我正在学习 ReactJS,并且正在使用 react-bootstrap.

构建我的第一个组件

我毫无问题地集成了模式,但我正在尝试检查浏览器是否不是 Internet Explorer 以启动模式框,并收到此错误:"Modal Box: "错误:重新呈现太多。 React 限制渲染的数量以防止无限循环。”可能是与正确更新状态相关的非常基本的事情,也许你可以帮助我,这是代码:

import React, { useState } from 'react';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';

function ModalStd () {

    const [show, setShow] = useState(false);

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);
    const customClass = "modal-std";

    function isIE() {
        var ua = navigator.userAgent;
        var is_ie = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
        return is_ie;
    }

    if (!isIE()) {
        handleShow(); // here is the issue I think
    }

    return (
        <>
            <Button variant="primary" onClick={handleShow}>
                Launch modal
            </Button>

            <Modal backdropClassName={customClass}
                   dialogClassName={customClass}
                   show={show} onHide={handleClose}
                   animation={false}>
                <Modal.Header closeButton>
                    <Modal.Title>Modal heading</Modal.Title>
                </Modal.Header>
                <Modal.Body></Modal.Body>
                <Modal.Footer>
                    <Button variant="secondary" onClick={handleClose}>
                        Close
                    </Button>
                    {/*<Button variant="primary" onClick={handleClose}>
                        Save Changes
                    </Button>*/}
                </Modal.Footer>
            </Modal>
        </>
    );
}

export default ModalStd;
``

将 handleShow 移动到 componentDidMount 喜欢:

useEffect(() => {
   if (!isIE()) {
        handleShow(); // here is the issue I think
    }
}, []) // it is equivalent to componentDidMount in React classes

并将 isIE 移到组件外部。因为每次更新组件(由于状态或道具更改)时,都会调用挂钩内的任何语句。