gpt4 book ai didi

javascript - 如何在 react 钩子(Hook)中有一个条件

转载 作者:行者123 更新时间:2023-11-30 13:51:34 25 4
gpt4 key购买 nike

我正在尝试在页面加载时加载引导模式,除非按下取消按钮。该功能的工作方式是,一旦页面加载,等待 2 秒并显示模态,除非按下取消按钮,在这种情况下不应显示模态,但是无论按下取消按钮如何,模态都会显示,

const Call = ({ t, i18n }) => {
const [modalShow, setModalShow] = useState(false);
const [cancelCall, setCancelCall] = useState(false);

useEffect(() => {
if (cancelCall) {
return;
} else {
setTimeout(() => {
setModalShow(true);
}, 2000);
}
}, [setModalShow, cancelCall]);

const handleCancelCall = e => {
setCancelCall(true);
console.log("cancel call pressed!");
};

return (
<Fragment>
<CallModal show={modalShow} onHide={() => setModalShow(false)} />

<button
type="button"
className="ml-4 btn btn-light"
onClick={e => handleCancelCall()}
>
Cancel
</button>
</Fragment>
);
};

如有任何帮助,我们将不胜感激。

最佳答案

尽管@Rajesh 的回答有效,但它导致了 2 次不必要的重新渲染(调用 setTimer)。我建议您只使用 ref 来跟踪计时器

const [modalShow, setModalShow] = useState(false);
const modalTimer = useRef(null);

useEffect(() => {
// the if (cancelCall) part in here was pointless
// because initial state is always false
modalTimer.current = setTimeout(() => setModalShow(true), 2000);
}, []);

const handleCancelCall = e => {
// on cancel, simply clear the timer
modalTimer.current && clearTimeout(modalTimer.current);
};

上面还删除了一些冗余代码和状态。

关于javascript - 如何在 react 钩子(Hook)中有一个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58133312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com