教程使用 React 钩子,但我正在使用类组件设置



我正试图按照本教程在我的React应用程序中实现谷歌分析与页面浏览量跟踪。但是,本教程使用React钩子,而我使用类组件设置了我的应用程序。我没有成功地将教程转换为类设置。我应该如何调整以使它适用于我的用例?

路由页,srcpagesindex.js:

// the function of concern
import useGaTracker from "../useGaTracker";
class Base extends Component {
render() {
useGaTracker();
// The hook inside a Class component, which is not allowed.
// But how can I make it work in my class components setting?
function withProps(Component, props) {
return function (matchProps) {
return <Component {...props} {...matchProps} />;
};
}
return (
<Router history={history}>
<Switch>
<Route exact path="/" component={Homepage} />
// Etc.

GA函数,src usegatacker .js:

import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
const useGaTracker = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
ReactGA.initialize(process.env.REACT_APP_GA_TAG);
setInitialized(true);
}, []);
useEffect(() => {
if (initialized) {
ReactGA.pageview(window.location.pathname + window.location.search);
}
}, [initialized, location]);
};
export default useGaTracker;

src index.js:

import Base from "./pages";
render(
<Provider store={store}>
<BrowserRouter>
<Base />
</BrowserRouter>
</Provider>,
document.getElementById("root")
);

在基类内部调用GA函数会产生错误:

错误:无效钩子调用。钩子只能在函数体内部调用函数组件的。

我应该如何重写这使它在我的类组件设置工作?

您可以让高阶组件创建功能组件,并在呈现给定的非功能组件之前让该组件调用useGaTracker:

const withGaTracker = (Component) => {
return (props) => {
useGaTracker();
return (
<Component {...props} />
);
};
};

然后传入Base组件

const BaseWithGaTracker = withGaTracker(Base);

和渲染结果在您的index.js替换<Base /><BaseWithGaTracker />


edit:更简单,只需要创建一个单独的功能组件来调用钩子并呈现它的子组件:

const GaTracker = ({children}) => {
useGaTracker();
return children;
}

然后在index.js中环绕<Base />

<GaTracker>
<Base />
</GaTracker>

如果你不打算在其他地方使用这个钩子,你也可以把它内联到新组件中。

最新更新