gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:36:43 25 4
gpt4 key购买 nike

我已经按照以下方式在一个类中定义了 Redux Action 创建者:

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”类或其对象上使用 bindActionCreators?

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

最佳答案

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

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

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

但是这样就没有捕获要点了。

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

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

关于javascript - 我们可以在类中定义的 redux Action Creators 上使用 bindActionCreators() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41423621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com