hoc + redux 和 redux 的区别 [英] different between hoc + redux and redux

查看:41
本文介绍了hoc + redux 和 redux 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 redux 包装成这样的 react hoc

I'm trying to wrap redux into a react hoc like this

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有什么区别?

If I going to write code in this way, is there any difference from directly connect redux in a performance way?

推荐答案

我不太了解关于以性能方式直接连接 redux"的问题,但您本质上有两个 HOC,redux 的 connect HOC 和你的新 withUser HOC.IMO,对于两个 HOC 和被装饰的组件的任何组合,性能将/应该是等效的.

I don't quite follow the question about "directly connecting redux in a performance way", but you've essentially two HOC's, redux's connect HOC and your new withUser HOC. IMO the performance will/should be equivalent for any composition of two HOCs and the component being decorated.

不过建议,将内部组件连接到商店并返回

Suggestion though, connect the inner component to the store and return it

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 步骤,因为您是在内部手动编写的,所以这里可能会有一些好处/改进,但我怀疑这很重要.

This removes the compose step since you've manually composed internally, so there may be some benefit/improvement here but I doubt it's significant.

争取金牌,减少基于类的组件的开销

Go for gold, reduce overhead of class-based component

const withUser = WrappedComponent => {
  const ComponentWithUser = props => <WrappedComponent {...props} />;

  const mapStateToProps = state => ({
    user: state.user,
  });

  return connect(mapStateToProps)(ComponentWithUser);
}

这篇关于hoc + redux 和 redux 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆