晚上好,请您建议一个解决方案,当用户导航到其他页面(例如,单击其他链接,按浏览器的后退按钮,但不更改到其他选项卡)时取消setTimeout。我尝试过窗口事件"unload",但它似乎不能像预期的那样工作。
我的应用程序是一个正常的倒计时,如果它计数到0,它会自动导航到分配的页面。出于某种目的,我需要禁用这个自动导航,如果用户点击其他链接,而它是计数。非常感谢。
import React, { useEffect } from 'react';
import {useHistory} from "react-router-dom";
const SucessPurchaseSubmit = () => {
const history = useHistory();
const navigateTo = () => history.push("/house-catalog");
useEffect(() => {
const time = document.querySelector(".time");
let count = 10;
var timer;
// automatic navigate to full catalog after 10 seconds
function countToNavigate(){
clearTimeout(timer);
time.innerHTML = count;
if (count === 0) {
navigateTo();
}
count -= 1;
timer = setTimeout(countToNavigate, 1000)
}
countToNavigate();
window.addEventListener("unload", () => {
clearTimeout(timer);
})
})
return (
<section className="success-purchase-submit">
<h1>Thank you so much for your information</h1>
<h3>One of our consultants will contact you very shortly</h3>
<h5>In the mean time, we will back to Full Catalog automatically after:</h5>
<h5 className="time">10</h5>
</section>
);
};
export default SucessPurchaseSubmit;
发布于 2020-10-16 10:34:35
我可能已经找到了你的问题的解决方案。
const FunctionalComponent = () => {
React.useEffect(() => {
return () => {
console.log("Bye");
};
}, []);
return <h1>Bye, World</h1>;
};
引用自- https://www.twilio.com/blog/react-choose-functional-components
您可以在useEffect()中使用clearInterval()。
useEffect()的工作方式类似于"OG“componentWillUnmount()。一旦重定向到新页面,这里就是clearInterval()的最佳位置。
发布于 2020-10-16 10:35:23
根据https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect的说法,您可以从useEffect返回一个函数,以便在卸载组件时进行清理。
因此,在useEffect函数的末尾,您可能可以添加:
return () => clearTimeout(timer);
要在移除组件时取消超时,请执行以下操作。
https://stackoverflow.com/questions/64387341
复制