React中显示弹出窗口的延迟



我仍在学习React,但情况是这样的——我有一个弹出窗口,当页面加载时会显示出来。我想将弹出窗口延迟5秒。使用useState是有效的,但当弹出窗口关闭时,它在5秒钟后再次出现,这是有道理的。根据我提供的信息,有没有其他方法可以管理react中弹出窗口的打开和关闭?

以下是到目前为止我使用useState 的情况

const PopupModal = ({url}) => {
const [open, setOpen] = useState(false);
const closeModal = () => setOpen(false);
React.useEffect(() => {
setTimeout(() => {
setOpen(true)
}, 5000)
}, [open])
if (!open) return null
return (
<Popup open={open} closeOnDocumentClick onClose={closeModal}>
<h1>Hey Hey!</h1>
</Popup>
);
};
export default PopupModal;

您的依赖数组是错误的。你在说"只要CCD_ 1改变就设置超时";。你应该让它成为";每当CCD_ 2函数改变(仅在第一次渲染上(时设置超时";

const PopupModal = ({url}) => {
const [open, setOpen] = useState(false);
const closeModal = () => setOpen(false);
React.useEffect(() => {
setTimeout(() => {
setOpen(true)
}, 5000)
}, [setOpen]) 
if (!open) return null // also this line is useless, since you're using the `open` prop of the Popup component
return (
<Popup open={open} closeOnDocumentClick onClose={closeModal}>
<h1>Hey Hey!</h1>
</Popup>
);
};
export default PopupModal;