公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:52010
  • 待审:67
  • 小程序:12
  • 文章:1106242
  • 会员:784

在这篇文章中,我将展示如何在 usestate hook react 应用程序中创建闭包。

我不会解释什么是闭包,因为关于这个主题的资源有很多,我不想重复。我建议阅读@imranabdulmalik的这篇文章。

简而言之,一个closure是(来自mozilla):

…捆绑在一起(封闭)的函数及其周围状态(词法环境)的引用的组合。换句话说,闭包使您可以从内部函数访问外部函数的作用域。在 javascript 中,每次创建函数时都会创建闭包,在函数创建时.

以防万一你不熟悉这个词词汇环境,你可以阅读@soumyadey的这篇文章或者这篇文章。

问题

在 react 应用程序中,您可能会意外创建属于使用 usestate 钩子创建的组件状态的变量的闭包。发生这种情况时,您将面临staleclosure问题,也就是说,当您引用状态的旧值时,它同时发生了变化,因此它不再相关。

poc

我创建了一个 demo react 应用程序,其主要目标是增加一个计数器(属于状态),该计数器可以在 settimeout 方法的回调中的闭包中关闭。

总之,这个应用程序可以:

显示计数器的值

计数器加1
启动计时器,在五秒后将计数器加1。
计数器加10

下图中,显示了应用程序的初始ui状态,计数器为零。

我们将分三步模拟柜台关闭:

    计数器加1

    启动计时器,五秒后加1

超时触发前增加10

5秒后,计数器的值为2.

计数器的期望值应该是12,但是我们得到2。

发生这种情况的原因是因为我们在传递给settimeout的回调中创建了关闭计数器,并且当触发超时时我们设置计数器从其旧值(即 1)开始。

settimeout(() => {
        setlogs((l) => [...l, `you closed counter with value: ${counter}\n and now i'll increment by one. check the state`])
        settimeoutinprogress(false)
        setstarttimeout(false)
        setcounter(counter + 1)
        setlogs((l) => [...l, `did you create a closure of counter?`])

      }, timeoutinseconds * 1000);

登录后复制

下面是app组件的完整代码

function app() {
  const [counter, setcounter] = usestate(0)
  const timeoutinseconds: number = 5
  const [starttimeout, setstarttimeout] = usestate(false)
  const [timeoutinprogress, settimeoutinprogress] = usestate(false)
  const [logs, setlogs] = usestate>([])

  useeffect(() => {
    if (starttimeout && !timeoutinprogress) {
      settimeoutinprogress(true)
      setlogs((l) => [...l, `timeout scheduled in ${timeoutinseconds} seconds`])
      settimeout(() => {
        setlogs((l) => [...l, `you closed counter with value: ${counter}\n and now i'll increment by one. check the state`])
        settimeoutinprogress(false)
        setstarttimeout(false)
        setcounter(counter + 1)
        setlogs((l) => [...l, `did you create a closure of counter?`])

      }, timeoutinseconds * 1000);
    }
  }, [counter, starttimeout, timeoutinprogress])

  function renderlogs(): react.reactnode {
    const listitems = logs.map((log, index) =>
      
  • {log} ); return {listitems}; } function updatecounter(value: number) { setcounter(value) setlogs([...logs, `the value of counter is now ${value}`]) } function reset() { setcounter(0) setlogs(["reset done!"]) } return (

    closure demo


    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() } ); } export default app;
  • 登录后复制

    解决方案

    解决方案基于useref钩子的使用,它可以让你引用渲染不需要的值。

    所以我们在app组件中添加:

    const currentcounter = useref(counter)
    

    登录后复制

    然后我们修改settimeout的回调,如下所示:

    settimeout(() => {
            setlogs((l) => [...l, `you closed counter with value: ${currentcounter.current}\n and now i'll increment by one. check the state`])
            settimeoutinprogress(false)
            setstarttimeout(false)
            setcounter(currentcounter.current + 1)
            setlogs((l) => [...l, `did you create a closure of counter?`])
    
          }, timeoutinseconds * 1000);
    

    登录后复制

    我们的回调需要读取计数器值,因为我们之前记录了当前值以递增它。

    如果您不需要读取值,只需使用功能符号更新计数器即可避免计数器关闭。

    seCounter(c => c + 1)
    

    登录后复制

    资源

    dmitri pavlutin 使用 react hooks 时要注意过时的闭包
    imran abdulmalik 掌握 javascript 中的闭包:综合指南

    keyur paralkar javascript 中的词法范围 – 初学者指南

    souvik paul react 中的陈旧闭包

    soumya dey 理解 javascript 中的词法范围和闭包

    subash mahapatra stackoverflow

    分享到:
    标签:React 关闭 陈旧
    用户无头像

    网友整理

    注册时间:

    网站:5 个   小程序:0 个  文章:12 篇

    • 52010

      网站

    • 12

      小程序

    • 1106242

      文章

    • 784

      会员

    赶快注册账号,推广您的网站吧!
    最新入驻小程序

    数独大挑战2018-06-03

    数独一种数学游戏,玩家需要根据9

    答题星2018-06-03

    您可以通过答题星轻松地创建试卷

    全阶人生考试2018-06-03

    各种考试题,题库,初中,高中,大学四六

    运动步数有氧达人2018-06-03

    记录运动步数,积累氧气值。还可偷

    每日养生app2018-06-03

    每日养生,天天健康

    体育训练成绩评定2018-06-03

    通用课目体育训练成绩评定