最近我正在使用 React 创建一个网站,我发现我使用了很多“setTimeOut()”,而且我从 React 文档中知道有时你需要在组件卸载时清理一些东西(说实话) ,我并不完全理解这个清理的事情),显然最近我看到一篇文章说“setTimeOut()”也需要清理,但是我如何清理我在“useEffect()”中调用的函数,我在在函数内使用“setTimeOut()”?
这是我的代码:
useEffect(() => {
createContent();
handleMobileContainerView();
});
const createContent = () => {
if (contentCompShowStatus) {
for (let key in btnStatus) {
if (btnStatus.hasOwnProperty(key)) {
if (btnStatus[key] === true) {
if (key === 'aboutBtn') {
delayContent('about-contents');
} else if (key === 'skillsBtn') {
delayContent('skills-contents');
} else if (key === 'projectsBtn') {
delayContent('projects-contents');
}
}
}
}
}
};
const delayContent = (content) => {
if (firstTime) {
setTimeout(() => {
setCurrentContent(content);
setFirstTime(false);
}, 200);
} else if (!firstTime) {
setTimeout(() => {
setCurrentContent(content);
}, 450);
}
};
正如您在上面的代码中看到的,“createContent()”位于“useEffect()”中,并且正在调用函数名称“delayContent()”,该函数使用“setTimeout()”。
这种情况需要清理吗?
遇到这种情况我该如何清理? (函数内部的函数使用“setTimeOut()”并在“useEffect()”中调用)
最佳答案
您可以在创建超时时返回timerId
。在unmount
上,您可以使用useEffect
的返回函数
进行清理。
卸载:
useEffect(() => {
const timerId = createContent();
handleMobileContainerView();
return () => {
clearTimeout(timerId);
};
}, []);
返回定时器ID:
const delayContent = (content) => {
let timerId;
if (firstTime) {
timerId = setTimeout(() => {
setCurrentContent(content);
setFirstTime(false);
}, 200);
} else if (!firstTime) {
timerId = setTimeout(() => {
setCurrentContent(content);
}, 450);
}
return timerId;
};
//所有代码:
function A() {
useEffect(() => {
const timerId = createContent();
handleMobileContainerView();
return () => {
clearTimeout(timerId);
};
}, []);
const createContent = () => {
if (contentCompShowStatus) {
for (let key in btnStatus) {
if (btnStatus.hasOwnProperty(key)) {
if (btnStatus[key] === true) {
if (key === "aboutBtn") {
return delayContent("about-contents");
} else if (key === "skillsBtn") {
return delayContent("skills-contents");
} else if (key === "projectsBtn") {
return delayContent("projects-contents");
}
}
}
}
}
};
const delayContent = (content) => {
let timerId;
if (firstTime) {
timerId = setTimeout(() => {
setCurrentContent(content);
setFirstTime(false);
}, 200);
} else if (!firstTime) {
timerId = setTimeout(() => {
setCurrentContent(content);
}, 450);
}
return timerId;
};
}
关于javascript - React setTimeout 和clearTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61341394/