reactjs - hoc + redux 和 redux 的区别
问题描述
我正在尝试将 redux 包装成这样的 react hoc
const WithUser = WrappedComponent => {
return class ComponentWithUser extends Component {
render() {
return <WrappedComponent {...this.props}>{this.props.children}</WrappedComponent>
}
}
}
const mapStateToProps = state => {
return {
user: state.user,
}
}
const composeWithUser = compose(connect(mapStateToProps, null), WithUser)
export default composeWithUser
如果我这样写代码,在性能上和直接连接redux有什么区别吗?
解决方案
我不太关注“以性能方式直接连接 redux”的问题,但你基本上有两个 HOC,redux 的connect
HOC 和你的新withUser
HOC。IMO 的性能将/应该与两个 HOC 的任何组合和被装饰的组件相同。
不过建议,将内部组件连接到商店并返回它
const withUser = WrappedComponent => {
class ComponentWithUser extends Component {
render() {
return <WrappedComponent {...this.props} />; // props.children included!
}
}
const mapStateToProps = state => ({
user: state.user,
});
return connect(mapStateToProps)(ComponentWithUser);
}
export default withUser;
由于您已在内部手动组合,因此这将删除该compose
步骤,因此此处可能会有一些好处/改进,但我怀疑它是否重要。
争取黄金,减少基于类的组件的开销
const withUser = WrappedComponent => {
const ComponentWithUser = props => <WrappedComponent {...props} />;
const mapStateToProps = state => ({
user: state.user,
});
return connect(mapStateToProps)(ComponentWithUser);
}
推荐阅读
- python - 将元组列表保存到文件中并作为列表再次读取
- amazon-web-services - 来自 EC2 的 AWS 中的 DNS 解析
- assembly - 如果为正则设置字节
- r - 在与 emmeans 交互中绘制缺少类别的结果
- python - 字符串索引超出范围 - 即使使用 * 1000 追加和初始化 - Python
- python - Django:无法分配字符串:类必须是类实例
- xcode12 - Xcode 12中的调试视图层次结构按钮在哪里
- node.js - express-subdomain 不解析任何子域
- javascript - Angular嵌套ngFor,从父循环中获取价值?
- bash - 如何在 bash 中将字符串附加到数组(列表)的末尾?