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

时间:2019-01-07 14:32:23

标签: reactjs 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存储替换数据库对象,使所有内容保持同步。

这是一种幼稚的方法,我正在寻找是否有更好的方法可以达到在整个应用程序生命周期内保持状态和数据库同步的目标。

1 个答案:

答案 0 :(得分:1)

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

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

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());
});
相关问题