问题
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