[英]Can we use bindActionCreators() on redux Action Creators defined in a class?
I have defined Redux action creators inside a class in the following manner: 我已经通过以下方式在类中定义了Redux动作创建者:
export class ActionCreator {
login() {
return { type: 'LOGIN_STATUS' };
}
fbLoginStatusOK(user) {
return { type: 'LOGIN_OK', user };
}
}
Then inside a React components I am using them like this: 然后在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>
);
}
}
How can I use bindActionCreators on the ' ActionCreator ' class or its object? 如何在“ ActionCreator ”类或其对象上使用bindActionCreators?
(So that every action creator is wrapped into a dispatch call so they may be invoked directly) (这样每个动作创建者都被包装到一个调度调用中,以便可以直接调用它们)
bindActionCreators
uses Object.keys
to iterate all function properties of an object and wrap them with a dispatch()
call. bindActionCreators
使用Object.keys
来迭代对象的所有函数属性,并使用dispatch()
调用包装它们。 In your case, even if you use something like bindActionCreators(new ActionCreator())
it won't work, because Babel
transpiles methods to non-enumerable properties. 在您的情况下,即使您使用诸如
bindActionCreators(new ActionCreator())
之类的方法,也无法正常工作,因为Babel
将方法转换为不可枚举的属性。
A possible solution might be declaring all methods in the constructor: 一个可能的解决方案可能是在构造函数中声明所有方法:
class ActionCreator {
constructor() {
this.login = () => ({ type: 'LOGIN_STATUS' });
}
}
but that would miss the point. 但这会遗漏重点。
Another possibility is to create your own utility, which would be similar to bindActionCreators
but would use Object.getOwnPropertyNames
instead of Object.keys
. 另一种可能性是创建自己的实用程序,该实用程序类似于
bindActionCreators
但将使用Object.getOwnPropertyNames
而不是Object.keys
。 However, you should be cautious here and make sure you only wrap the methods you need (ignore constructor
, for example). 但是,在此应谨慎,并确保只包装所需的方法(例如,忽略
constructor
)。
I'm also wondering what's your motivation? 我也想知道你的动机是什么? isn't a bit of an overhead using a class instead of a plain object?
使用类而不是普通对象有点负担吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.