Redux:异步和同步调度
Redux: async and sync dispatches
我的 react/redux 应用程序中有一个多页用户注册表。
当用户点击 "next page," 时,它会发出调用以更新本地 redux 存储(而非服务器)中的用户配置文件。
当他们点击最后一页上的 "Submit" 时,我目前有一个点击处理程序:
clickHandler: function(formData) {
dispatch(updateProfileInStore(formData);
dispatch(saveProfileToServer());
}
我的问题是:我能否 100% 确定带有我的用户配置文件的 Redux 存储会在调用第二次调度之前更新?
我担心在某些情况下,配置文件可能会在 最后一页表单数据添加到其中之前写入我的数据库。
不能保证。您可以做的是传递 saveProfileToServer
新表单数据使其更新状态并将更新后的表单数据发送到服务器。
setState() does not immediately mutate this.state but creates a
pending state transition. ... There is no
guarantee of synchronous operation of calls to setState and calls may
be batched for performance gains.
在这里添加同步行为的唯一方法是使用 redux thunk 或 sagas。一个 redux thunk returns promise 解决了,在 sagas 中,我们可能必须观察 updateProfileInStore 调度的成功操作,它需要调用 saveProfileToServer。
我的 react/redux 应用程序中有一个多页用户注册表。
当用户点击 "next page," 时,它会发出调用以更新本地 redux 存储(而非服务器)中的用户配置文件。
当他们点击最后一页上的 "Submit" 时,我目前有一个点击处理程序:
clickHandler: function(formData) {
dispatch(updateProfileInStore(formData);
dispatch(saveProfileToServer());
}
我的问题是:我能否 100% 确定带有我的用户配置文件的 Redux 存储会在调用第二次调度之前更新?
我担心在某些情况下,配置文件可能会在 最后一页表单数据添加到其中之前写入我的数据库。
不能保证。您可以做的是传递 saveProfileToServer
新表单数据使其更新状态并将更新后的表单数据发送到服务器。
setState() does not immediately mutate this.state but creates a pending state transition. ... There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
在这里添加同步行为的唯一方法是使用 redux thunk 或 sagas。一个 redux thunk returns promise 解决了,在 sagas 中,我们可能必须观察 updateProfileInStore 调度的成功操作,它需要调用 saveProfileToServer。