使用钩子会导致无限循环

时间:2020-08-19 20:53:55

标签: reactjs

我有一个模式组件,当用户打开网站时,该组件只需出现一次。这是我的代码:

import React, { useState } from 'react';
import { Modal, Button } from 'antd';

function WelcomeModal() {

    const [visibility, setVisibility] = useState(true);

    function handleVisibility() {
        setVisibility(!visibility);
    }

    return (
        <div>
           <Modal
            title="Vertically centered modal dialog"
            centered
            visible={visibility}
            onOk={handleVisibility()}
            onCancel={handleVisibility()}
           ></Modal>
        </div>
    )
}

export default WelcomeModal;

我创建了一个名为visibility的状态,该状态最初为true,在用户单击模式上的CancelOK之后,我尝试将可见性更改为false,因此该模式关闭。问题是出现以下错误:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

我该如何解决?

1 个答案:

答案 0 :(得分:1)

看起来您的意思是将onOk函数作为onCancel()道具传递给Modal组件,但是您不小心用括号SELECT * FROM ( select id, column from table WHERE column IS NOT NULL minus select id, column from table where TRANSLATE(TRANSLATE(TRANSLATE(column,'','!@#$%^&*()-=+/\{}[];:.,<>?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'),'','''"')) = '' AND column IS NOT NULL )来调用它。

这意味着当组件首次渲染时,它将调用该函数,该函数将更改状态,从而触发重新渲染,然后再次调用该函数,依此类推。