different between hoc + redux and redux

微笑、不失礼 提交于 2021-02-11 12:44:54

问题


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

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


回答1:


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;

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);
}


来源:https://stackoverflow.com/questions/62909234/different-between-hoc-redux-and-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!