首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >活动期间的Zustand状态一致性和计时

活动期间的Zustand状态一致性和计时
EN

Stack Overflow用户
提问于 2021-05-11 02:33:31
回答 1查看 183关注 0票数 1

好了,这是一个难题。我有一个select输入,并且我使用。我看到了不一致的状态,并且没有得到我怀疑的东西。

它看起来像这样。

代码语言:javascript
复制
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 ...
}

select有两个值:“一”和“二”。

如果我把这些东西console.log出来,我就会看到问题和bug。我不能在这个函数中使用状态变量。它不会像我想的那样等待、解决或表现。

因此,对于我的select,如果我在1和2之间切换,我会得到这个有趣的行为:

代码语言:javascript
复制
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
}

当在select输入上从"one“切换到"two”时,console.log输出如下所示。

代码语言:javascript
复制
two  // event.value
one  // the in-scope zustand variable sortBy as a read after the set

当切换到select上的"two“时,我得到了相反的结果,但这些变量不是相同的吗?

代码语言:javascript
复制
one  // event.value
two  // the set variable sortBy

当在select上切换到"one“时。因为有些东西并不像我想的那样是一致的或解决的。

我认为zustand状态变量应该是一致的(特别是当我添加await时,eslint告诉我await确实对这个函数有影响)。这对我来说现在不是问题,因为我可以将参数用于我需要的任何东西。但我只是觉得我在这里错过了一些重要的东西,我希望当我需要依赖于状态改变或一致性存储时,Zustand不会让我上钩。

EN

回答 1

Stack Overflow用户

发布于 2021-05-11 03:42:35

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

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67475892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档