首页 > web前端 > js教程 > 正文

React:陈旧的关闭

王林
发布: 2024-08-21 06:19:02
原创
372 人浏览过

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

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

简而言之,闭包(来自 Mozilla):

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

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

问题

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

POC

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

简而言之,这个应用程序可以:

  • 显示计数器的值
  • 计数器加 1
  • 启动计时器,在五秒后将计数器加 1。
  • 计数器加 10

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

React: stale closure

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

  1. 计数器加 1

React: stale closure

  1. 启动计时器,五秒后加 1

React: stale closure

  • 超时触发前增加 10 React: stale closure

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

React: stale closure

计数器的预期值应该是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);
登录后复制

遵循应用程序组件的完整代码。

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

    1. Set the counter to preferred value
    2. Start a timeout and wait for {timeOutInSeconds} to increment the counter (current value is {counter})
    3. 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 中的闭包:综合指南
    • JavaScript 中的 Keyur Paralkar 词法范围 – 初学者指南
    • React 中的 Souvik Paul Stale 闭包
    • Soumya Dey 理解 JavaScript 中的词法范围和闭包
    • Subash Mahapatra stackoverflow

    以上是React:陈旧的关闭的详细内容。更多信息请关注PHP中文网其他相关文章!

    来源:dev.to
    本站声明
    本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责声明 Sitemap
    PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!