Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/409.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将配置传递给Redux操作创建者的正确方法_Javascript_Configuration_Redux_Redux Thunk - Fatal编程技术网

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

Javascript 将配置传递给Redux操作创建者的正确方法,javascript,configuration,redux,redux-thunk,Javascript,Configuration,Redux,Redux Thunk,将配置注入动作创作者的“重复”方式是什么 考虑一个异步操作创建者: export function login(username, password) { return (dispatch, getState) => { const service = Auth.createService(config); // <- that's the one service.login(username, password).then((data) =

将配置注入动作创作者的“重复”方式是什么

考虑一个异步操作创建者:

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);
        });
    };
}
由于多种原因,它是次优的,不允许您为特定服务实例覆盖它们

使用中间件(在redux thunk上的一些扩展)将提供注入配置的能力,但是:

  • 它很可能已经通过
    getState
    注入,因为对我来说,配置是应用程序状态的一部分,尤其是在它是可编辑的情况下

  • 它仍然不允许对每个创建者进行覆盖

  • 将配置从容器组件直接传递给动作创建者
    this.props.dispatch(登录名(用户名、密码、配置)),对我来说,是极其冗长的。

    我认为来自Este的这篇文章相当简洁:

    // 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

    export function login(username, password) {
       return ({ dispatch, getState, authService }) => {