问题
I am developing a desktop app with react for UI and electron.
So, for now, I am fetching data from the server and saving it in the state using React's Context API to update the UI.
I am keeping the state and the function to add, remove and update state in the renderer process and with IPC I am sharing the data between renderer process through main process (as it should be).
But as the application is scaling I need a better approach. Something like a central state (if that's a thing).
P.S. can I use a database along with the Electron app if there is any real-time database such as rxdb?
回答1:
I had this exact same problem and I used electron-redux (https://github.com/hardchor/electron-redux). I was also using react for my UI.
回答2:
The best way to have a 'master state' is to use React-Redux.
Redux can do what Context does and more. It also has lots of libraries for listening for realtime updates from servers. The most popular at the time is React-Redux-Firebase, which connects your Redux store
with your Firebase database.
Most developers agree on the fact that Redux takes some time to set up, but is definitely worth the time invested. I have personally used React-Redux-Firebase and I can assure you that all real-time updates will be in your Redux store
within 250ms.
Firebase is also free up to a certain point (check Firebase Pricing).
In order to access your Redux state
in a component, your need to follow 3 steps:
STEP 1: Create a mapStateToProps
const that contains all the stuff you want from your store
.
const mapStateToProps = state => ({
customers: state.customers,
books: state.books
})
STEP2: Create an actions
const that contains any functions you have in an actions.js
or similar file and you want to call
import { fetchCustomers } from './actions.js'
const actions = {
fetchCustomers
}
Remember that any fetching from your API can (and should) be done from there.
STEP 3: Export your component with Redux's connect
function, including your mapStateToProps
and actions
consts.
export default connect(mapStateToProps, actions)(myComponent);
Redux is rather complicated to be explained in a single stackoverflow answer, so I suggest you take a look at the docs or follow a tutorial. You should be able to figure everything out in your first or second day of development. It is absolutely worth the time.
来源:https://stackoverflow.com/questions/59776005/how-to-share-state-reactbetween-electrons-multiple-windows