【发布时间】:2024-04-14 05:45:01
【问题描述】:
我想要一个应用程序 HOC 来包装每个组件视图。 此 HOC 对用户进行身份验证并设置 Google Analytics 跟踪。 我正在升级到路由器 4,但无法使其正常工作。
它给了我以下错误 -
TypeError: (0 , _AppWrapper2.default) is not a function
这可能与我创建 HOC 的方式有关。 有什么想法吗?
routes.js
export default (
<Switch>
<Route exact path="/" component={AppWrapper(Home)} />
<Route exact path="/channels" component={AppWrapper(Channels)} />
</Switch>
);
const AppWrapper = (WrappedComponent) => {
return class AppWrapperComponent extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const page = this.props.location.pathname;
this.trackPage(page);
}
componentWillReceiveProps(nextProps) {
const currentPage = this.props.location.pathname;
const nextPage = nextProps.location.pathname;
if (currentPage !== nextPage) {
this.trackPage(nextPage);
}
}
trackPage = page => {
GoogleAnalytics.set({
page,
...options,
});
GoogleAnalytics.pageview(page);
};
render() {
return (
<div>
{this.state.isMounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools />}
<WrappedComponent {...this.props.chidren} />
</div>
);
}
}
【问题讨论】:
-
*.com/questions/47099094/… 这可能会有所帮助
-
你需要在routes.js中用大括号导入AppWrapper,像这样:import { AppWrapper } from './wrapper'
标签: reactjs react-redux react-router-v4 higher-order-components