我们可以在 class 中定义的 redux Action Creators 上使用 bindActionCreators() 吗?

Can we use bindActionCreators() on redux Action Creators defined in a class?

我按以下方式在 class 中定义了 Redux action creators:

export class ActionCreator {

    login() {
        return { type: 'LOGIN_STATUS' };
    }

    fbLoginStatusOK(user) {
        return { type: 'LOGIN_OK', user };
    }
}

然后在 React 组件中,我像这样使用它们:

class Login extends React.Component {

    login(e) {
        e.preventDefault();
        a = new ActionCreator(); // Simplified
        dispatch(a.login());
    };

    render() {
        return (
            <div>
                <h1>Login</h1>
                <p>
                    <a href="#" onClick={this.login}>Login</a>
                </p>
            </div>
        );
    }
}

如何在“ActionCreator”class 或其对象上使用 bindActionCreators?

(以便每个动作创建者都被包装到一个调度调用中,以便可以直接调用它们)

bindActionCreators 使用 Object.keys 迭代对象的所有函数属性,并用 dispatch() 调用包装它们。 在您的情况下,即使您使用 bindActionCreators(new ActionCreator()) 之类的东西也不会起作用,因为 Babel 将方法转换为不可枚举的属性。

一个可能的解决方案可能是在构造函数中声明所有方法:

class ActionCreator {
    constructor() {
        this.login = () => ({ type: 'LOGIN_STATUS' });
    }
}

但那样会失去重点。

另一种可能性是创建您自己的实用程序,它与 bindActionCreators 类似,但会使用 Object.getOwnPropertyNames 而不是 Object.keys。但是,您在这里应该小心并确保只包装您需要的方法(例如忽略 constructor)。

我也想知道你的动机是什么?使用 class 而不是普通对象不是有点开销吗?