好了,这是一个难题。我有一个select输入,并且我使用。我看到了不一致的状态,并且没有得到我怀疑的东西。
它看起来像这样。
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之间切换,我会得到这个有趣的行为:
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输出如下所示。
two // event.value
one // the in-scope zustand variable sortBy as a read after the set当切换到select上的"two“时,我得到了相反的结果,但这些变量不是相同的吗?
one // event.value
two // the set variable sortBy当在select上切换到"one“时。因为有些东西并不像我想的那样是一致的或解决的。
我认为zustand状态变量应该是一致的(特别是当我添加await时,eslint告诉我await确实对这个函数有影响)。这对我来说现在不是问题,因为我可以将参数用于我需要的任何东西。但我只是觉得我在这里错过了一些重要的东西,我希望当我需要依赖于状态改变或一致性存储时,Zustand不会让我上钩。
发布于 2021-05-11 03:42:35
这似乎是React在setState中遇到的相同问题和行为。在React中使用setState时,即使这是一个常见的陷阱,您也不会这样做。值不会立即更新,这种思维方式不适用于并发GUI。
https://twitter.com/acemarke/status/1389376376508227592
在Zustand的例子中,在调用set之后,它甚至可能没有要触发的回调函数。换句话说,这在这个时候是行不通的。
https://stackoverflow.com/questions/67475892
复制相似问题