React 和 Redux:管理 Redux 自定义中间件列表

React and Redux: Managing Redux Custom Middleware List

对于我的 React 应用程序,我构建了许多自定义中间件并在 applyMiddleware() 中传递了它们。因为我有太多,所以 redux 存储文件看起来有点拥挤。将它们全部传递到 applyMiddleware() 或将它们导入函数中的单独文件然后在 applyMiddleware() 中传递该函数以保持其清洁是一个好习惯吗?

// Redux store
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const store = createStore(
  reducers,
  composeEnhancers(
    applyMiddleware(...xMdl, ...yMdl, ...zMdl, ...nAmountsOfMdl),
  )
);

我更喜欢使用 combineReducers 为减速器创建组。 分享一下我的中间件设置,希望对你有帮助!

store.config.js :

import rootReducer from '../_reducers'

export const history = createBrowserHistory()

export const store = configureStore();

export default function configureStore(preloadingState) {
  const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  const store = createStore(
    rootReducer(history),
    preloadingState,
    composeEnhancer(
      applyMiddleware(
        routerMiddleware(history),
        thunk,
      ),
    ),
  )

  return store
}

index.js(在 reducers 文件夹中):

const rootReducer = (history) => combineReducers({
    router: connectRouter(history),
    single: combineReducers({
        post: postReducer,
        guide: guideReducer,
        course: courseReducer,
        lesson: lessonReducer,
        exercise: exerciseReducer,
    }),
    bank: combineReducers({
        posts: postsReducer,
        guides: guidesReducer,
        courses: coursesReducer,
        lessons: lessonsReducer,
        exercises: exercisesReducer,
    }),
    melodition: playerReducer,
    user: combineReducers({
        profile: profileReducer,
        favorites: favoriteReducer,
    }),
    snackbar: snackbarReducer,
    auth: authReducer,
});

export default rootReducer;

注意:我在 connected-react-router 的一个大型项目上这样做过,也许它对每个项目都没有好处。