[英]React Hook “useInterval” cannot be called inside a callback
I'm trying to setup a progress bar for a backend action that can take a while to complete. 我正在尝试为可能需要一段时间才能完成的后端操作设置进度条。
I simplified the code in Codesandbox to reproduce the problem, in my Codesandbox, when clicking the button, I run useInterval to get a new random cat picture every 4 seconds and update my hook. 我简化了Codesandbox中的代码以重现此问题,在Codesandbox中,单击按钮时,我运行useInterval每隔4秒获取一张新的随机猫图片并更新我的钩子。
As I understand, the problem is because I'm calling a Hook inside a custom Hook (useInterval), but I don't know another way to do this because native setInterval does not work with Hooks. 据我了解,问题是因为我在自定义的Hook(useInterval)中调用了Hook,但是我不知道另一种方法,因为本机setInterval无法与Hook一起使用。
I used the use-interval package 我使用了use-interval包
You don't have to wrap useInterval
with useEffect
. 您不必包装
useInterval
与useEffect
。 Internally useInterval
calls useEffect
to do it work. 内部
useInterval
调用useEffect
可以正常工作。
And you can change values passed to useInterval
in component and new values will be applied correctly. 您可以更改组件中传递给
useInterval
值,新值将正确应用。 You can change delay or callback arguments and useInterval
will apply them. 您可以更改延迟或回调参数,并且
useInterval
将应用它们。
To showcase, I've added stop button, which stops retrieving cats. 为了展示,我添加了停止按钮,该按钮停止检索猫。
Here is working solution with cats :-) 这是猫的工作解决方案 :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.