实时更新异步存储/数据存储
我有一个React Native应用程序,用户可以编辑存储在React State中的文本。我想实现自动助理,以便实时持续使用用户输入。
我已经用异步的持久性代替了我的状态,但发现我正在遇到种族条件:
- 我的父母组件从持久性中获取文本。
- 用户输入新文本,该文本会触发回调以更新给定文本的新文本。
- 如果用户输入文本过快,在持久性更新之前,我的父组件获取了新的,更新的文本,则在旧文本上触发了下一个async更新,从而导致冲突。
特别是,这是AWS数据存储发生的。我尚未尝试使用异步存储,但鉴于它也使用异步/等待,我想我会遇到同一问题。
骇客方法将以更长的间隔进行更新,但我假设我设置的任何间隔都足够长,以至于每个异步更新在下一个之前完成。它也更加复杂,因为我必须保留本地状态,该状态包含用户在背景中与异步存储/数据存储同步时所看到的内容。
是否有一种很好的方法可以用持久版本替换React状态,该版本不需要额外的逻辑处理异步竞赛条件?在理想的世界中,某种usepersistedstate
挂钩为我管理这一切,暴露了与usestate
完全相同的行为?
为了举一个竞赛条件的示例,说文本为a
,我输入b
,然后是c
:
- 第一个数据存储更新:<代码> a + <代码> b
- (预期第二个数据存储<代码> ab +
+
c
) - 实际第二个数据存储更新如果输入太快: a +
c
- 数据存储结果有些冲突,例如,将两个更新合并到生产
abac
I have a react native application where a user can edit a text which is stored in react state. I would like to implement autosaving so that user input is persisted in real time.
I have replaced my state with async persistence but have found that I am running into a race condition:
- My parent component fetches the text from persistence.
- The user inputs new text, which triggers a callback to update the given text with the new content.
- If the user inputs text too quickly, before the persistence has updated and my parent component has fetched the new, updated text, the next async update is triggered on the old text, causing a conflict.
In particular, this happened with AWS DataStore. I have not tried using async storage, but given it also uses async/await I imagine I will run into the same problem.
A hacky approach would be updating at longer intervals but I'm assuming whatever interval I set will be long enough that each async update completes before the next. It's also more complicated as I have to keep local state which contains what the user sees while syncing that with the async storage/DataStore in the background.
Is there a nice way to replace react state with a persisted version that doesn't require a load of extra logic handling async race conditions? In an ideal world, some sort of usePersistedState
hook which manages this all for me, exposing the exact same behaviour as useState
?
To give an example of the race condition, say the text is a
, and I type in b
followed by c
:
- First DataStore update:
a
+b
- (Expected second DataStore update
ab
+c
) - Actual second DataStore update if input is too fast:
a
+c
- DataStore result is some conflict, e.g. merging both updates to produce
abac
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论