ReactJS,react-bootstrap,模式框:“错误:重新渲染过多。 React限制了渲染次数以防止无限循环。”

问题描述 投票:0回答:1

我正在学习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;
``
reactjs bootstrap-modal state onload react-bootstrap
1个回答
0
投票

将handleShow移至componentDidMount,例如:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.