将配置传递给 Redux 操作创建者的正确方法
Posted
技术标签:
【中文标题】将配置传递给 Redux 操作创建者的正确方法【英文标题】:Proper way to pass configuration into Redux action creators 【发布时间】:2016-07-30 17:10:09 【问题描述】:将配置注入动作创建者的“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
(和所有其他服务)需要一些配置,通常定义如下:baseUrl
、headers
等。
通过以下方式将它们 require
d 放在 AuthService
本身中:
import configfrom '../config/globalConfig`;
由于多种原因不是最理想的,并且不允许您针对特定服务实例覆盖它们。
使用中间件(redux-thunk
的一些扩展)将提供注入配置的能力,但是:
它很可能已经通过getState
注入,因为对我来说,配置是应用程序状态的一部分,尤其是在可编辑的情况下
它仍然不允许覆盖基于每个创建者
将配置从容器组件直接传递给动作创建者this.props.dispatch(login(username, password, config));
,对我来说非常冗长。
【问题讨论】:
【参考方案1】:我认为这个来自 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
。
【讨论】:
以上是关于将配置传递给 Redux 操作创建者的正确方法的主要内容,如果未能解决你的问题,请参考以下文章