如何保持React状态与MySQL数据库同步 [英] How to keep the React state in sync with MySQL database

查看:217
本文介绍了如何保持React状态与MySQL数据库同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:我正在构建一个简单的日历Web应用程序,该服务器的前端使用React,后端使用MySQL。该应用程序在首次安装时从服务器检索所有事件的列表,将其显示给用户并允许进行CRUD操作。一切正常。

Scene: I am building a simple calendar web-app that uses React for the front-end and MySQL on the back-end for the server. The app retrieves a list of all the events from the server when it is first mounted, displays them to the user and allows for CRUD operations. Everything works as expected.

问题:在创建,更新或删除操作中,我应该:

Question: On a Create, Update or Delete operation, should I:


  1. 独立地更新数据库和状态。

  1. Update the database and the state "independently".

更新数据库,再次调用服务器以检索新的事件列表,然后将状态设置为此新列表。

Update the database, make another call to the server to retrieve the new list of events and then set the state equal to this new list.

完全执行其他操作。

Impetus :我的印象是应该有一个单一来源数据,感觉就像上面的第一个选项导致了我有两个源的情况,在某些情况下可能会变得不同步。

Impetus: I am working under the impression that there should be a "single source of truth" for my data, and it feels likes the first option above creates a situation where I have two "sources" that could in some situation become out of sync.

推荐答案

1和2.都是正确的,这实际上取决于您要实现的目标。您可以尝试使用乐观更新,这意味着在提交这些操作时,您将状态更改为成功(大多数情况下应该如此),并在操作失败时进行更正。数据库/后端由于某种原因。这样可以创建良好的前端体验。在这种情况下,您还可以在操作后获取新数据。

Both 1. and 2. are correct, it really depends on what are you trying to achieve. You can try to use optimistic updates which means that when submitting these operations you change the state as if it was successful (which should be the case most of the time) and make a correction if the operation failed in the database/backend for some reason. This creates a nice front-end experience. In these cases you can also get the new data after the operation.

如果数据库中的数据可以从多个来源更改,则您需要定期且最有可能在更改之后获取它,并相应地更新前端。

If the data on the database can change from multiple sources, you need to get it periodically and after changes most probably, and update your front-end accordingly.

如果您是唯一一个操作数据(至少需要在状态中使用该数据)的情况,第一种情况应该可以工作。在这种情况下,后端/数据库仍应以已执行操作的状态响应,以帮助您管理状态。您还可以在操作挂起时显示某种加载指示符,而不是优化状态更新。

Case 1. should work if you are the only one manipulating the data (which you need to have in the state at least). In this case the back-end / database should still respond with the status of the performed operation in order to help you manage the state. You can also display some kind of loading indicator while the operation is pending instead of optimisticaly updating the state.

您可以在此处详细了解乐观更新: https://www.guidesmiths.com / en / news-and-blog / anatomy-a-react-application-optimistic-updates-22

You can read more about optimistic updates here: https://www.guidesmiths.com/en/news-and-blog/anatomy-of-a-react-application-optimistic-updates-22

这篇关于如何保持React状态与MySQL数据库同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆