在这篇文章中,我将展示如何在 usestate hook react 应用程序中创建闭包。
我不会解释什么是闭包,因为关于这个主题的资源有很多,我不想重复。我建议阅读@imranabdulmalik的这篇文章。
简而言之,一个closure是(来自mozilla):
…捆绑在一起(封闭)的函数及其周围状态(词法环境)的引用的组合。换句话说,闭包使您可以从内部函数访问外部函数的作用域。在 javascript 中,每次创建函数时都会创建闭包,在函数创建时.
以防万一你不熟悉这个词词汇环境,你可以阅读@soumyadey的这篇文章或者这篇文章。
问题
在 react 应用程序中,您可能会意外创建属于使用 usestate 钩子创建的组件状态的变量的闭包。发生这种情况时,您将面临staleclosure问题,也就是说,当您引用状态的旧值时,它同时发生了变化,因此它不再相关。
poc
我创建了一个 demo react 应用程序,其主要目标是增加一个计数器(属于状态),该计数器可以在 settimeout 方法的回调中的闭包中关闭。
总之,这个应用程序可以:
显示计数器的值计数器加1 启动计时器,在五秒后将计数器加1。计数器加10
下图中,显示了应用程序的初始ui状态,计数器为零。
counter value: {counter}
follow the istructions to create a closure of the state variable counter
set the counter to preferred value start a timeout and wait for {timeoutinseconds} to increment the counter (current value is {counter}) increment by 10 the counter before the timeout
{ renderlogs() }
微信扫一扫
支付宝扫一扫