我刚刚发现在我的反应项目中使用HOC的惊人好处。
我的问题是在组件上调用多个HOC函数是否有任何性能损失?
示例
export default withState(withLabel(withTheme(MyComponent)))
这当然只有render
一个组件,但是看看我的反应开发工具,我可以看到输出的HOC组件三层深。这是否需要警惕,或者是否有更好的方法在组件上调用多个HOC?
答案 0 :(得分:2)
您的语法等同于:
<StateProvider>
<LabelProvider>
<ThemeProvider>
<MyComponent />
</ThemeProvider>
</LabelProvider>
</StateProvider>
性能受到影响将来自这些HOC的实施方式。您可能需要查看它们中的每一个。
示例:
总之,没有硬规则。您的主要关注点应该是了解这些HOC的作用,并尝试限制应用程序的不必要的重新渲染。
答案 1 :(得分:0)
这个答案不完全是关于性能的,但是当我不得不一次使用几个高阶组件包装同一组件时,我要做的一件事是创建一个主要的高阶组件,该组件将调用我需要的所有高阶组件,所以我可以只包装一个。
创建一个主要的高阶组件使其更易于重用,并且包装的组件 更加简洁易读。
看这个例子:
“主要”高阶组件调用所有常用组件:
import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { withStyles, createStyles, Theme, WithStyles } from '@material-ui/core/styles';
import withSnack, { Snack } from '../CommonComponents/SnackBar/WithSnack';
import withCancelable, { Cancelable } from '../CommonComponents/WithCancelable';
interface Props {
snack: Snack;
cancelable: Cancelable;
history: any;
};
type WithCommon =
(TargetComponent: React.ComponentClass, componentsToInclude?: string[], styles?: any, mapStateToProps?: any, mapDispatchToProps?: any) => React.ComponentClass<Props, any>;
const withCommon = (
TargetComponent: any,
componentsToInclude: string[] | undefined = undefined,
styles: any | undefined = undefined,
mapStateToProps: any | undefined = undefined,
mapDispatchToProps: any | undefined = undefined
): WithCommon => {
const withCommonComponent = (props: Props) => (<TargetComponent {...props} />)
let resultComponent: any = withCommonComponent;
if (mapStateToProps || mapDispatchToProps) {
resultComponent = connect(
mapStateToProps,
mapDispatchToProps
)(withCommonComponent);
}
if (styles) {
resultComponent = withStyles(styles)(resultComponent);
}
if (componentsToInclude) { // "extra" components to wrap the target
if (componentsToInclude.length) {
if (componentsToInclude.some(c => c === 'router')) {
resultComponent = withRouter(resultComponent);
}
if (componentsToInclude.some(c => c === 'snack')) {
resultComponent = withSnack(resultComponent);
}
if (componentsToInclude.some(c => c === 'cancelable')) {
resultComponent = withCancelable(resultComponent);
}
} else { // if array is empty then include them all (avoids typing the same ones every time you need to have them all)
resultComponent = withCancelable(withSnack(withRouter(resultComponent)));
}
}
return resultComponent;
};
export interface Common extends WithStyles {
snack: Snack,
cancelable: Cancelable,
history: any,
};
export default withCommon;
然后是上面的主要组件所包裹的组件:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Avatar from '@material-ui/core/Avatar';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import Dialog from '@material-ui/core/Dialog';
import { createStyles, Theme } from '@material-ui/core/styles';
import TextFieldOutlined from '../CommonComponents/Form/TextFieldOutlined';
import { hideSignin } from '../Redux/ActionCreators'
import Auth from '../Auth/Auth';
import Form from '../CommonComponents/Form/Form';
import Loading from '../CommonComponents/Loading';
import withCommon, { Common } from '../CommonComponents/WithCommon';
const styles = (theme: Theme) =>
createStyles({...});
interface Props extends Common {
show: boolean;
hideSignin(): void;
};
interface State {...}
class SignIn extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.handleEmailchange = this.handleEmailchange.bind(this);
this.handlePasswordchange = this.handlePasswordchange.bind(this);
this.signin = this.signin.bind(this);
}
signin(e: any): void {
if (!e.currentTarget.form.reportValidity()) {
return;
}
e.preventDefault();
this.setState({ loading: true });
Auth.signin(
this.state.email,
this.state.password,
(promise: Promise<any>) => this.props.cancelable.setCancelable('signin', promise),
)
.then(() => {
this.props.history.push('/');
})
.catch((err: any) => {
this.props.snack.error(err.message);
})
.finally(() => {
this.setState({ loading: false });
});
}
render() {
const { classes } = this.props;
return (
<Dialog
open={this.props.show}
onClose={() => this.props.hideSignin()}
>
<Paper className={classes.paper}>
<Loading loading={this.state.loading} />
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5" className={classes.label}>
Sign in
</Typography>
<Form submitButtonText="Sign in" onSubmit={this.signin}>
<TextFieldOutlined required label="Email Address" type="email" onChange={this.handleEmailchange} focused />
<TextFieldOutlined required label="Password" type="password" onChange={this.handlePasswordchange} />
</Form>
</Paper>
</Dialog>
);
}
}
(SignIn as React.ComponentClass<Props, State>).propTypes = {
classes: PropTypes.object.isRequired,
} as any;
const mapStateToProps = (state: any) => {
return {
show: state.signin.show,
};
}
const mapDispatchToProps = (dispatch: any) => {
return {
hideSignin: () => dispatch(hideSignin()),
}
}
// Empty array will make it include all the "extra" higher order components
export default withCommon(SignIn, [], styles, mapStateToProps, mapDispatchToProps) as any;
// Or you could specify which extra components you want to use:
// export default withCommon(SignIn, ['router', 'cancelable'], styles, mapStateToProps, mapDispatchToProps) as any;
// Or some nulls if you just want to connect the store:
// export default withCommon(SignIn, null, null, mapStateToProps, mapDispatchToProps) as any;
答案 2 :(得分:-3)
我不会用它。当你查看你的MyComponent
组件时,了解道具的来源是很复杂的。使用这种模式还有很多缺点。无论如何,如果您决定使用HOC
,请以正确的方式使用它,例如
const withDetails = Component => {
const C = props => {
// do something
}
// assign display & wrapped names - easier to debug
C.displayName = `withRouter(${Component.displayName))`
C.WrappedComponent = Component;
return C;
}
我建议不要使用HOC
来查看render props
反应模式。 Michael Jackson(react-router creator)的Use a Render Prop!
文章对此进行了详细解释。
希望它有意义。