![](/img/trans.png)
[英]Is function component that uses React-hook can be render inside from a class component
[英]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.