繁体   English   中英

教程使用 React Hook,但我在 Class 组件设置中工作

[英]Tutorial uses a React Hook, but I'm working in a Class Component setting

我正在尝试按照本教程在我的 React 应用程序中实施带有网页浏览跟踪功能的 Google Analytics。 但是,本教程使用 React 挂钩,而我使用 class 组件设置我的应用程序。 我无法将教程翻译成 class 设置。 我应该如何调整以使其适用于我的用例?

路由页面,\src\pages\index.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 function,\src\useGaTracker.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")
);

在 Base class 中调用 GA function 会产生错误:

错误:无效挂钩调用。 钩子只能在 function 组件的内部调用。

我应该如何重写它以使其在我的 Class 组件设置中工作?

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

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

然后传入Base组件

const BaseWithGaTracker = withGaTracker(Base);

并通过将<Base />替换为<BaseWithGaTracker />在您的 index.js 中呈现结果。


编辑:更简单,只需制作一个调用钩子并呈现其子组件的功能组件:

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

然后将它包裹在 index.js 中的<Base />周围

<GaTracker>
  <Base />
</GaTracker>

如果您不打算在其他任何地方使用该挂钩,您也可以将其内联到新组件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM