如何创建一个过时的闭包,比如react的useeffect钩子中的闭包,而不使用实际的useeffect钩子?

pwuypxnk  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(249)

我知道闭包是如何工作的,但我无法理解如何在react中创建过时的闭包 useEffect 在没有穷举依赖项数组的情况下。为此,我试图复制一个过时的闭包,就像react的一样 useEffect 不使用 useEffect ,但我无法创建它。我的代码不会创建过时的闭包,而是在每个间隔上记录一个正确的值。请看一下下面的片段并告诉我:
我做错了什么?我应该怎么做才能创建一个像我们在react中得到的那样陈旧的闭包呢 useEffect 当我们不提供完整的依赖项数组时(参考代码在文章末尾)
当我们没有在useeffect中给出详尽的依赖项时,为什么会创建过时的闭包?为什么代码不在 useEffect hook的回调只使用词法作用域,就像普通函数一样,并打印实际值?

function createIncrement(incBy) {
  let value = 0;

  function increment() {
    value += incBy;
    console.log(value);
  }

  function useEffect(fun) {
    fun()
  }

  useEffect(function() {
    setInterval(function log() {
          // what should I do to create a stale closure here?
          // So that if I change the value it should show me the old value
          // as it does when using React's useEffect without exhaustive dependencies array

          console.log(`Count is: ${value}`); // prints correct value each time
        }, 2000);
  });

  setTimeout(() => {
    increment(); // increments to 5
    increment(); // increments to 6
  }, 5000);

  return [increment];
}

const [increment] = createIncrement(1);
increment(); // increments to 1
increment(); // increments to 2
increment(); // increments to 3
increment(); // increments to 4

为完整起见,以下是使用react的useeffect的代码片段,其中我们没有为react的useeffect提供详尽的依赖项数组,因此创建了一个过时的闭包:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function WatchCount() {
  const [count, setCount] = useState(0);

  useEffect(function () {
    setInterval(function log() {
      // No matter how many times you increase the counter 
      // by pressing the button below,
      // this will always log count as 0
      console.log(`Count is: ${count}`);
    }, 2000);
  }, []);

  return (
    <div>
      {count}
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<WatchCount />, rootElement);

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题