【问题标题】:Create persistent redux state backed by MongoDB in Electron + React在 Electron + React 中创建由 MongoDB 支持的持久化 redux 状态
【发布时间】:2016-09-04 08:35:42
【问题描述】:

我有一个基于react-electron-boilerplate 的应用程序,使用完全相同的一组模式。我的应用程序使用mongodb 作为持久层,连接到远程数据库以维护其状态。

为了获取当前状态,我通常在我的一个动作控制器中执行如下操作 (app/actions/<whatever>.js)

export function stepForward(step, action) {
  if (_.isUndefined(step)) {
    step = db.collection('steps').findOne({ current: true }).index; // just an example
  }
  return {
    type: STEP_FORWARD
  };
}

但是,这并不一定要写入数据库。我想要的是保持一个持久状态,也就是说,只要它发生变化,就将这个状态写入数据库(是的,我知道这对于大型应用程序来说可能代价高昂)。

这可以用 redux 和 mongodb 实现吗?

【问题讨论】:

    标签: javascript reactjs redux electron react-redux


    【解决方案1】:

    虽然我从 Ian 提到的 finalReducer 模式开始,但结果证明使用 Redux 中间件要容易得多:

    import {createStore, combineReducers, applyMiddleware} from 'redux'
    
    const persist = store => next => action => {
      next(action)
      persistData(store.getState())
    }
    
    const store = createStore(<reducer>, undefined, applyMiddleware(persist))
    

    【讨论】:

      【解决方案2】:

      绝对可以实现。在创建您的商店之前,我会将您所有的减速器组合成最终的减速器。这个最终的 reducer 将作用于 any 动作并将状态持久化到 Mongo。一些伪代码为例:

      import { createStore, combineReducers } from 'redux';
      import <all of your other reducers>
      
      const reducers = combineReducers({
          <other reducers here>
      });
      
      const finalReducer = (state, action) => {
          const nextState = reducers(state, action);
      
          //use whatever module you use to write to mongo...
          persistToMongo(nextState);
      
          return nextState;
      };
      
      const store = createStore(finalReducer, undefined);
      

      希望这足以让您的创意源源不断。如果您需要更多帮助或澄清,请告诉我,否则,祝您好运!

      【讨论】:

      • 我知道这是旧的,但是对于任何路人来说,这违背了 redux 的 3 个原则之一:使用纯函数进行更改。纯函数没有任何副作用(例如修改状态、保存到数据库、从燃烧的建筑物中救出狗等等……)。减速器应该是纯函数。
      • 回顾这一点(一年多后)我同意杰克的观点。我肯定会使用 daviestar 建议的中间件。
      猜你喜欢
      • 2019-03-11
      • 1970-01-01
      • 2020-12-25
      • 2016-02-17
      • 2018-08-14
      • 1970-01-01
      • 2019-05-30
      • 2018-05-21
      • 1970-01-01
      相关资源
      最近更新 更多