即使回调在状态更改后很好地触发,它也不会收到更新的状态版本 [英] Callback doesn't receive the updated version of state even when it fires well after state changes

查看:22
本文介绍了即使回调在状态更改后很好地触发,它也不会收到更新的状态版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用功能组件.我知道 setColor 异步更改 color 的值.但是,即使在 color 更新后执行良好,我的回调函数也不会收到更新版本的 color(蓝色).这是我的代码的抽象版本:

I'm using a functional component. I'm aware setColor changes the value of color asynchronously. However, my callback function doesn't receive the updated version of color (blue) even when it executes well after color has been updated. Here's an abstract version of my code:

let [color, setColor] = useState("red");

useEffect(() => {
  setColor("blue");
  setTimeout(() => {
    console.log(color);
  }, 5000)
}, []);

(这是一个沙箱:https://codesandbox.io/s/falling-cherry-17ip2?file=/src/App.js)

我唯一的猜测是 setColor 函数几乎创建了一个新的 color 变量 &console.log 在引用旧的 color 时卡住了.

My only guess is that the setColor function almost creates a new color variable & console.log is stuck referencing the old color.

故障排除

  1. 我知道辅助 useEffect 有可能在状态改变时执行我的回调.但是,这很不方便,因为我正处于复杂逻辑的中间,我只想在某些条件下执行回调.

  1. I'm aware a secondary useEffect has the potential to execute my callback when state changes. However, this is inconvenient because I'm right in the middle of complex logic where I only want the callback to execute under certain conditions.

我也知道 useRef 变量几乎会立即更新,因此这是一个替代方案.

I'm also aware useRef variables update pretty much immediately and so that'd be an alternative.


尽管如此,问题仍然存在:为什么 color 的更新值没有被记录 &我可以在主要 useEffect 中做些什么来访问最新版本的 color 状态?


Nevertheless, the question still stands: why isn't the updated value of color being logged & is there anything I could do in the primary useEffect to access the latest version of color state?

推荐答案

  1. setColor 改变状态.
  2. 阶段的变化使函数组件再次执行
  3. 函数组件的新调用重新运行 let [color, setColor] = useState("red");
  4. 这会将 color 的当前状态分配给 color 变量.
  5. 时光流逝
  6. 传递给 setTimeout 的箭头函数运行.这结束上一个 color 变量,它被分配了 状态.
  1. setColor changes the state.
  2. The change in stage makes the Function Component execute again
  3. The new invoke of the Function Component reruns let [color, setColor] = useState("red");
  4. This assigns the current state of color to the color variable.
  5. Time passes
  6. The arrow function passed to setTimeout runs. This has closed over the previous color variable which was assigned the old state.

这篇关于即使回调在状态更改后很好地触发,它也不会收到更新的状态版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆