【问题标题】:Zustand state consistency and timing during an event事件期间的状态一致性和时间安排
【发布时间】:2021-08-01 04:17:37
【问题描述】:

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

看起来像这样。

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 这些东西出来,我会看到问题和错误。我不能在这个函数内部使用状态变量。它不会像我认为的那样等待、解决或运行。

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

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 确实对此函数有影响时)。现在这对我来说不是问题,因为我可以将参数用于我需要的一切。但我只是觉得我在这里遗漏了一些重要的东西,我希望 Zusand 在我需要依赖某处的状态更改或一致的存储时不会抓住我。

【问题讨论】:

    标签: javascript zustand


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-10
      • 2011-05-11
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多