react怎么与MySQL,如何保持React状态与MySQL数据库同步

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:

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.

Do something else entirely.

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值