将配置传递给Redux动作创建者的正确方法

时间:2016-04-09 12:05:05

标签: javascript configuration redux redux-thunk

什么被认为是将配置注入动作创建者的“Redux”方式?

考虑异步操作创建者:

export function login(username, password) {
    return (dispatch, getState) => {
        const service = Auth.createService(config); // <- that's the one

        service.login(username, password).then((data) => {
            const {token} = data;
            dispatch(success(token));
        }).catch((err) => {
            Logger.log(err);
        });
    };
}

正如您所看到的那样 - AuthService(以及所有其他服务)需要一些配置,通常会定义以下内容:baseUrlheaders等。

通过以下内容requireAuthService d放入其中:

import configfrom '../config/globalConfig`;

由于多种原因而次优,不允许您为特定服务实例覆盖

使用中间件(某些扩展名超过redux-thunk)将提供注入配置的能力,但是:

  1. 很可能已经通过getState注入,因为对我来说,配置是应用程序状态的一部分,特别是如果它是可编辑的

  2. 仍然不允许基于每个创作者的覆盖

  3. 将容器组件中的配置直接传递给动作创建者this.props.dispatch(login(username, password, config));,对我来说非常冗长。

1 个答案:

答案 0 :(得分:2)

我认为来自Este的injectMiddleware非常整洁:

// Like redux-thunk with dependency injection.
const injectMiddleware = deps => ({ dispatch, getState }) => next => action =>
  next(typeof action === 'function'
    ? action({ ...deps, dispatch, getState })
    : action
  );

这可以让你编写像

这样的动作创建者
export function login(username, password) {
   return ({ dispatch, getState, authService }) => {

并在初始化中间件时注入authService