事件期间的 Zustand 状态一致性和时间

问题描述

好的,这是一个谜题。我有一个选择输入,我使用 Zustand 作为状态。我看到不一致的状态并且没有得到我怀疑的东西。

看起来像这样。

const handleSortChange = async (event) => {
  // set a state variable
  setSort(event.value)

  // do a network call using sortBy and other things
  // the call is wrong when using sortBy and I'll replace
  // this bug with console.log statements below ...
}

选择有两个值:“一”和“二”。

如果我将这些东西 console.log 出来,我就会看到问题和错误。我不能在这函数内部使用状态变量。它不会像我认为的那样等待、解决或表现。

所以对于我的选择,如果我在 1 和 2 之间切换,我会得到这个有趣的行为:

const handleSortChange = async (event) => {
  // set a state variable
  setSort(event.value)  // this sets sortBy
  console.log(event.value)
  console.log(sortBy)   // this is the zustand state variable that is in scope
  // I expect these would be the same,but they aren't!  :O
}

在选择输入上从“一”切换到“二”时,console.log 输出如下所示。

two  // event.value
one  // the in-scope zustand variable sortBy as a read after the set

在选择上切换到“两个”时,我得到相反的结果但这些变量不一样?

one  // event.value
two  // the set variable sortBy

在选择上切换到“一”时。因为有些事情不像我想的那样一致或解决

我认为 zustand 状态变量会是一致的(尤其是当我添加 await 并且 eslint 告诉我 await 确实对这个函数有影响时)。这对我来说现在不是问题,因为我可以将参数用于我需要的一切。但我只是觉得我在这里错过了一些重要的东西,我希望 Zustand 在我需要依赖某个地方的状态更改或一致存储时不会找我。

解决方法

这似乎与 React 对 setState 的问题和行为相同。使用 React 中的 setState 你不会这样做,即使这是一个常见的陷阱。值不会立即更新,这种思维方式不适用于并发 GUI。

https://twitter.com/acemarke/status/1389376376508227592

在 Zustand 的情况下,它甚至可能没有在调用 set 后触发的回调函数。换句话说,这在这个时候是行不通的。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...