首页 > 解决方案 > 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有什么区别吗?

标签: reactjsreact-redux

解决方案


我不太关注“以性能方式直接连接 redux”的问题,但你基本上有两个 HOC,redux 的connectHOC 和你的新withUserHOC。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);
}

推荐阅读