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

问题描述 投票:0回答:2

好的,这是一个谜题。 我有一个选择输入,并且使用 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 ...
}

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

如果我将这些内容控制台记录下来,我就会看到问题和错误。 我无法在该函数内部使用状态变量。 它不会等待、解决或按照我想象的方式运行。

因此,对于我的选择,如果我在一和二之间切换,我会得到这个有趣的行为:

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 状态变量会是一致的(特别是当我添加等待并且 eslint 告诉我等待确实对此函数有效时)。 现在这对我来说不是问题,因为我可以使用该参数来满足我需要的一切。 但我只是觉得我在这里错过了一些大东西,我希望当我需要在某个地方依赖状态更改或一致存储时,Zustand 不会抓住我。

javascript zustand
2个回答
2
投票

这似乎与 React 与

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

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

对于 Zustand,它甚至可能没有在调用

set
后触发的回调函数。 换句话说,目前这不起作用。


0
投票

是的,我也觉得这很令人困惑。要访问最新状态,我们需要从商店获取:

const handleSortChange = async (event) => {
  setSort(event.value)  
  console.log(event.value)
  console.log(sortBy) //  event.value != sortBy
  console.log(store.getState().sortBy) // event.value == sortBy
}
© www.soinside.com 2019 - 2024. All rights reserved.