英文:
Can redux state be out of sync?
问题
如果我快速连续点击两次Sorter
,第二次点击时,redux_state_obj
是否可能过时,即它是否使用了第一次点击之前的redux_state_obj
更新?
英文:
function Sorter({ redux_state_obj, set }) {
const handle_click = () => {
const new_state = JSON.parse(JSON.stringify(redux_state_obj))
// update new_state based on redux_state_obj
set(new_state)
}
return <div onClick={handle_click}>button</div>
}
Suppose I click on the Sorter
repeatedly extremely fast twice. Could the redux_state_obj
be outdated in the second click, i.e. it is using the redux_state_obj
before the first click made its update?
答案1
得分: 1
JavaScript在单线程中执行,使用事件循环和任务队列来确保一致性并允许异步操作。
这里有一篇关于它是如何工作以及如何安排任务的好文章:https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/#try-it
任务队列的最简单算法如下:
- 检查任务队列是否有任务。
- 如果没有任务 -> 转到步骤1。
- 如果有最老的任务 -> 出队它,等待它完成,然后转到步骤1。
在你的情况下,首次点击将安排执行handle_click
函数,然后它将被执行(同步修改redux状态)。如果你在函数执行时点击(主线程被占用),浏览器将仅安排一个任务来处理这第二次点击,只有在函数返回后才会完成第二次调用handle_click
,因此第二次调用handle_click
将使用最新的状态值执行。
话虽如此,Redux或React库中可能存在异步代码,它将状态更新安排到另一个任务中。在这种情况下,您的第二个handle_click
调用将在计划的状态更新之前发生。例如,React中的一个已知示例是setState
方法:https://sentry.io/answers/forget-set-state-is-async/
但要发生这种情况,您必须比浏览器执行处理程序函数更快地点击,这可以是纳秒级别的时间差,所以您需要是整个野西最快的手,或者您的处理程序必须编写得非常糟糕。
英文:
Javascript is executed in the single thread with the use of event loop and task queue to ensure consistency and allow for asyncronous operations.
Here is a nice article about how it works and how tasks are scheduled: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/#try-it
The simplest algorithm of the task queue is this:
- Check queue for tasks
- If there are none -> go to step 1
- If there is an oldest task -> dequeue it, wait for it to complete, then go to step 1
In your case, first click will schedule execution of handle_click
function,
then it will be executed (modifying your redux state syncronously).
If you click when your function is executing (main thread is occupied), browser will just schedule a task to handle this second click and it will be completed only after the return of your function. So second call of handle_click
will be executed with up-to-date state values.
That said, there can be asyncronous code in the redux or react libraries, that schedules state update to another task. In this case, your second handle_click
call will occur BEFORE that scheduled state update. For example one of the known example of that in react is setState
method: https://sentry.io/answers/forget-set-state-is-async/
But for that situation to occure, you have to click faster than browser executes your handler function, which can be an order of nanoseconds, so you need to be the fastest hand in the whole wild west or your handler must be written very poorely.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论