【发布时间】:2019-04-02 08:21:51
【问题描述】:
我最近在处理复杂的 HOC 以及如何仅通过其中定义的新道具而不是其他任何道具。 更准确地说,假设我的 HOC 使用了其他扩展其属性的 HOC,例如
const withSession = (WrappedComponent) => {
class SessionProvider extends React.PureComponent {
constructor(props) {
super(props);
this.login = this.login.bind(this);
}
login() {
console.log('login'); // this will dispatch some action
// this.props.dispatch...
}
render() {
return (
<WrappedComponent
doLogin={this.login}
{...this.props}
/>
);
}
}
const mapStateToProps = null;
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
const withConnect = connect(mapStateToProps, mapDispatchToProps);
return compose(
withConnect,
withRouter,
)(injectIntl(SessionProvider));
};
这里SessionProvider 使用dispatch 和injectIntl 将属性附加到其props。但是,我不想将这些道具传递给包装的组件。这个想法是有一个SessionProvider HOC,它有一些 API 调用,但只用login 扩展包装的组件。
我注意到如果保留{...this.props},则被包装的组件还将获得我不想通过的HOC 使用的所有props。
所以我想通过更改 HOC 渲染方法来明确定义要通过的属性通过分解this.props:
render() {
const { dispatch, intl, ...otherProps } = this.props;
return <WrappedComponent doLogin={this.login} { ...otherProps} />;
}
但是,如果 WrappedComponent 本身具有 dispach 或 intl 属性,则这些属性不会通过 HOC。
我在做什么有什么问题吗?有更好的方法吗?我错过了什么吗?
【问题讨论】:
标签: reactjs