如何解决使用 setInterval 并清除间隔时,无法对卸载的组件警告执行 React 状态更新为什么?
我正在测试一个组件,该组件使用钩子每 30 秒更新一次值。它通过每三十秒调用 setInterval
来实现。我正在清除钩子的 useEffect
钩子中的这个间隔。当我在 Jest 中运行测试时,我得到 Warning: Can't perform a React state update on an unmounted component
。我正在清除 useEffect 钩子的清理函数中的间隔,但这仍然不能解决问题。
如果我在清理函数中将 isCanceled
布尔值设置为 true
,并在调用 setter 之前检查该值的真实性,我将不再遇到此问题。我的问题是:我不太明白为什么会这样。我知道在组件卸载之后和 clearInterval
被调用之前 setInterval
的内容运行之前一定有一个间隙,但我没有看到它。谁能解释一下?预先感谢您的帮助。
const useCalculatedMinutes = (time: EpochTime): string => {
let isCanceled = false;
const [mins,setMins] = useState(getMinutesFromNow(time));
const THIRTY_SECONDS = 30000;
const updateMinutesRegularly = () => {
return setInterval(() => {
// if (!isCanceled) { // This check will prevent the warning from happening.
setMins(getMinutesFromNow(time));
// }
},THIRTY_SECONDS);
};
useEffect(() => {
const interval = updateMinutesRegularly();
return () => {
// isCanceled = true; // Doing this to indicate the component is Now unmounted; this works.
clearInterval(interval);
};
},[mins]);
return mins;
};
编辑:我也在使用 Jest 的 runOnlyPendingTimers
函数。测试如下:
it('increments the time after one minute',async () => {
const ONE_MINUTE_FROM_Now = Date.Now() + 60100 * 1;
renderDashboardScreen();
await waitForElementToBeRemoved(screen.getByText(/Loading.../));
expect(screen.getByText(/10 mins/)).toBeInTheDocument();
await waitFor(() => {
jest
.spyOn(global.Date,'Now')
.mockImplementation(() => ONE_MINUTE_FROM_Now);
jest.runOnlyPendingTimers(60000);
});
expect(await screen.findByText(/11 mins/)).toBeInTheDocument();
});
Additionally,I have other tests in the file. If I comment out all of the others,I don't get the warning. If I uncomment any of the other tests,I get the warning again.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。