javascript - 事件期间的状态一致性和时间安排
问题描述
好的,这是一个谜题。我有一个选择输入,我正在使用 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 不会抓住我。
解决方案
这似乎与 React 具有相同的问题和行为setState
。在setState
React 中你不会这样做,即使这是一个常见的陷阱。该值不会立即更新,这种思维方式不适用于并发 GUI。
https://twitter.com/acemarke/status/1389376376508227592
在 Zusand 的情况下,它甚至可能没有在调用后触发的回调函数set
。换句话说,这在这个时候是行不通的。
推荐阅读
- android-studio - Flutter项目中的AaptProcess
- vb.net - Visual Basic 中的多个升序面板
- c# - 无法单击带有样式的日历日期
- jenkins - 如何将 Jenkins 构建历史从一台服务器复制到另一台服务器?
- python - Flask 和 HTML:重定向 json 响应以显示在同一页面的底部,而不是在单独的页面上显示响应
- lua - vb.net 用户的 Lua 脚本
- javascript - HTML5 样板中的“未捕获的 ReferenceError:未定义导出”
- java - 创建具有可变生成量的树状结构
- ios - iOS 金属 3d 网格顶点位置
- python - 在 Python 中将集合转换为冻结集的复杂性