问题
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.
回答1:
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.
You can read more about optimistic updates here: https://www.guidesmiths.com/en/news-and-blog/anatomy-of-a-react-application-optimistic-updates-22
来源:https://stackoverflow.com/questions/49470280/how-to-keep-the-react-state-in-sync-with-mysql-database