javascript - Redux:打开和关闭中间件

标签 javascript reactjs redux middleware

我正在寻找一种打开和关闭中间件的方法。我引入了一个教程功能——我通过使用“指导”中间件检查每个操作来倾听用户正在使用 UI 做什么。如果用户点击正确的地方,他就会进入教程的下一步。但是,仅当教程模式打开时才需要此行为。有什么想法吗?

const store = createStore(holoApp, compose(applyMiddleware(timestamp, ReduxThunk, autosave, guidance),
window.devToolsExtension ? window.devToolsExtension() : f => f)); 

目前我的解决方案是在 guidanceState reducer 中保持“on”开关并在中间件中对其进行脏检查:

const guidance = store => next => action => {

    let result = next(action)

    const state = store.getState();
    const { guidanceState } = state;
    const { on } = guidanceState;

    if (on) {

 ....

但是,大约 95% 的时间教程模式会关闭,所以一直检查每个 Action 感觉有点脏,好吧,脏...;) 还有其他方法吗?

最佳答案

不要在中间件中做有状态的事情(除非你有一个很好的状态管理模式,比如 Sagas)。如果可以避免的话,根本不要对你的中间件堆栈做有状态的事情。 (如果您必须这样做,@TimoSta's solution 是正确的)。

相反,使用 reducer 管理您的游览:

const finalReducer = combineReducers({
  // Your other reducers
  tourState: tourReducer
});

function tourReducer(state = initalTourState, action) {
  switch(action.type) {
    case TOUR_LAST_STEP:
      return /* compose next tour step state here */;
    case TOUR_NEXT_STEP:
      return /* compose last tour step state here */;
    case TOUR_CLOSE:
      return undefined; // Nothing to do in this case
    default:
      return state;
  }
}

然后,在您的应用程序中使用 tourState 的当前状态移动突出显示,如果 tourState 中没有任何内容,则关闭游览。

store.subscribe(() => {
  const state = store.getState();
  if (state.tourState) {
    tourManager.setTourStep(state.tourState);
  } else {
    tourManager.close();
  }
});

您也不必使用有状态的游览管理器 - 如果您使用的是 React,它可能只是一个组件,它使用 connect 包装器提取 tourState并呈现 null 如果没有状态:

// waves hands vigorously
const TourComponent = (props) => {
  if (props.currentStep) return <TourStep ...props.currentStep />;
  return null;
}

关于javascript - Redux:打开和关闭中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383260/

相关文章:

javascript - EmberJS : toggleProperty set all properties of a Component to a default value

javascript - 在 native react 中,如何将base64图像转换为jpg然后保存到临时路径?

javascript - 将值作为对象提交

javascript - 为什么 mapStateToProps 只以这种奇怪的方式更新? (对此可以做些什么?)

javascript - 为什么 node.js 提示我的数组?

javascript - jquery each 用于所有文本框

javascript - 单选按钮组验证。使用 alert Reactjs 突出显示所有未选中的单选按钮问题

css - 路径不适合 SVG

javascript - 消除不同mapStateToProps之间的冗余

javascript - 提供给 `selected` 的 `String` 类型的无效 Prop `Calendar`, `Date` 的预期实例?