如何在反应钩子中有一个条件



除非按下取消按钮,否则我正在尝试在页面加载时加载引导模式。该功能的工作方式是,一旦页面加载,等待 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);
};

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

这是因为,在页面加载时,您的cancelCall将始终为假,因此您将注册超时事件。

发布该用户单击按钮,但还需要删除已注册的事件。尝试:

const Call = ({ t, i18n }) => {
const [modalShow, setModalShow] = useState(false);
const [cancelCall, setCancelCall] = useState(false);
// Save the timer id in state
const [timer, setTimer] = useState(null);
useEffect(() => {
if (cancelCall) {
return;
} else {
const timer = setTimeout(() => {
setModalShow(true);
}, 2000);
setTimer(timer)
}
}, [setModalShow, cancelCall]);
const handleCancelCall = e => {
setCancelCall(true);
// On cancel, check if timer is not null. If not clear the timer from queue
!!timer && window.clearTimeout(timer);
setTimer(null)
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>
);
};

最新更新