保持数据库与Redux存储(Redux中间件)同步的最佳方式是什么



因此,我的目标是使MongoDB数据库与应用程序的当前状态保持同步。例如,每当我的状态发生变化(例如,项目名称)时,在调度操作、发出reducer信号并更改状态后,该更改将保存到数据库中。

例如,我有一个具有以下结构的状态对象:

const INITIAL_STATE = {
name: "",
triggered: false,
isUnique: false
};

因此,当用户更改项目名称时,名称更改将首先由状态本身完成,在状态更改后,会调用DB来更改项目名称。

为了模拟数据库的更改,我使用localStorage来实现相同的目的:

function handshake() {
return ({ dispatch, getState }) => next => action => {
// send action to next Middleware
next(action);
const db = JSON.parse(localStorage.getItem("temporaryDB"));
const presentState = getCurrentState(getState());
if(db) {
const areStatesEqual = isEqual(db, presentState);
if(!areStatesEqual) return localStorage.setItem("temporaryDB", JSON.stringify(presentState));
return;
}
localStorage.setItem("temporaryDB", JSON.stringify(presentState));
};
}
export default function configureStore(initialState = {}) {
return createStore(
rootReducer,
applyMiddleware(handshake())
)
}

getCurrentState只是一个获取当前状态的实用程序函数。无论如何,我的逻辑是使用Redux中间件,并在数据库对象和存储对象之间寻找更改。如果对象在任何方面都不同,我会用Redux存储替换DB对象,使所有内容保持同步。

这是一种天真的方法,我想看看是否有更好的方法来实现我的目标,即在整个应用程序的生命周期中保持状态和数据库同步。

我认为您只需要订阅商店并听取那里发生的所有更改。

例如,加载/保存状态以保持同步的两个功能

export const loadState = () => {/*the DB logic*/}
export const saveState= () => {/*the DB logic*/} 

然后你可以用这些函数组成redux,并通过调用loadState()来初始化状态

import { loadState, saveState } from "where theyare"
const syncWithDBstate= loadState();
const store = createStore(
rootReducer,
syncWithDBstate,
composeWithDevTools(applyMiddleware(thunk)) // here I am suing the chrome devtool extention
);
store.subscribe(() => {
saveState(store.getState());
});

最新更新