【发布时间】:2018-06-28 22:41:52
【问题描述】:
我知道这个问题已经得到解答,但我无法处理出了什么问题。我有一个包装函数:
const withTracker = (WrappedComponent, partnerTrackingCode, options = {}) => {
const trackPage = (page) => {
ReactGA.set({
page,
options
});
ReactGA.pageview(page);
};
class HOC extends Component {
componentDidMount() {
ReactGA.initialize(partnerTrackingCode);
const page = this.props.location.pathname;
trackPage(page);
}
componentWillReceiveProps(nextProps) {
const currentPage = this.props.location.pathname;
const nextPage = nextProps.location.pathname;
if (currentPage !== nextPage) {
trackPage(nextPage);
}
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return HOC;
};
export default withTracker;
我在这里称呼它:
export default (props) => {
const MainComponent = (
<div>
...
</div>
);
if (props.partnerTrackingCode) {
return (
withTracker(MainComponent, props.partnerTrackingCode)
);
}
return (<div />);
};
当定义跟踪代码并调用 withTracker 时,即使 mainComponent 是一个组件,它也会向我显示此错误:A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object
我也尝试用空 div 替换 WrappedComponent:
return(<div />)
但还是同样的错误
【问题讨论】:
-
建议:不要多次退货。将它们存储在一个变量中并有一个返回 () 将它们连接在一起
标签: javascript reactjs higher-order-components