React GA 设置 - usePageTracking 无法正常工作,收到警告“[react-ga] ReactGA.initialize must be called first...”
React GA Setup - usePageTracking not working correct, get warning "[react-ga] ReactGA.initialize must be called first..."
在本地主机上的 React 应用程序中,应用程序 returns 出现以下 2 个警告:
要在 React 中设置 GA,我们正在尝试使用我们的 usePageTracking 挂钩。来自
usePageTracking
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import ReactGA from 'react-ga';
import config from '../config';
const usePageTracking = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!window.location.href.includes('localhost')) {
ReactGA.initialize(config.gaTrackingId);
}
setInitialized(true);
}, []);
useEffect(() => {
if (initialized) {
ReactGA.pageview(location.pathname + location.search);
// ReactGA.set({ userId: userId }); // don't have userId in usePageTracking
}
}, [initialized, location]);
};
export default usePageTracking;
在我们的 App.js 文件中使用这个钩子,我们调用这个钩子,然后我们检查用户是否已经登录(localStorage 中的 auth-token),并在抓取用户信息时,代码(尝试)使用 ReactGA.set
.
在 ReactGA 中设置 userId
App.js
import React, { useState, useEffect } from 'react';
import usePageTracking from './hooks/usePageTracking';
function App() {
usePageTracking();
// Check User Is Logged In
useEffect(() => {
const checkLoggedIn = async () => {
// Grab Auth Token From Local Storage
let token = localStorage ? localStorage.getItem('auth-token') : window.localStorage.getItem('auth-token');
if (token === null) {
localStorage.setItem('auth-token', '');
token = '';
}
try {
// Check If Valid Token
const apiBaseUrl = config.url.API_URL;
const tokenResponse = await Axios.post(`${apiBaseUrl}/users/tokenIsValid`, null, { headers: { 'x-auth-token': token } });
// if valid token exists...
if (tokenResponse.data) {
// get the user
const userRes = await Axios.get(`${apiBaseUrl}/users/`, {
headers: { 'x-auth-token': token }
});
// Set userId for Google Analytics
ReactGA.set({ userId: userRes.data._id });
// And Set User Data, Giving User Logged-In Access
setIsUserLoading(false);
setUserData({ token, user: userRes.data });
} else {
setIsUserLoading(false);
}
} catch (err) {
setIsUserLoading(false);
}
};
checkLoggedIn();
}, []);
// render rest of the app...
// ...
}
如何修改代码来解决这些警告?由于抛出这 2 个警告,可能 React GA 没有正确设置?
如果它不是 localhost 但将 initialized
设置为 true,则您只是在初始化;
if (!window.location.href.includes('localhost')) {
ReactGA.initialize(config.gaTrackingId);
}
setInitialized(true) // for localhost we never invoked ReactGA.initialize
所以在本地主机上,没有初始化库,有一个对 ReactGA.pageview
的调用,因此应该先调用错误消息 ReactGA.initialize
。
您应该在调用 pageview
时检查 localhost
。
if (!window.location.href.includes('localhost') && initialized) {
ReactGA.pageview(location.pathname + location.search);
}
在本地主机上的 React 应用程序中,应用程序 returns 出现以下 2 个警告:
要在 React 中设置 GA,我们正在尝试使用我们的 usePageTracking 挂钩。来自
usePageTracking
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import ReactGA from 'react-ga';
import config from '../config';
const usePageTracking = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!window.location.href.includes('localhost')) {
ReactGA.initialize(config.gaTrackingId);
}
setInitialized(true);
}, []);
useEffect(() => {
if (initialized) {
ReactGA.pageview(location.pathname + location.search);
// ReactGA.set({ userId: userId }); // don't have userId in usePageTracking
}
}, [initialized, location]);
};
export default usePageTracking;
在我们的 App.js 文件中使用这个钩子,我们调用这个钩子,然后我们检查用户是否已经登录(localStorage 中的 auth-token),并在抓取用户信息时,代码(尝试)使用 ReactGA.set
.
App.js
import React, { useState, useEffect } from 'react';
import usePageTracking from './hooks/usePageTracking';
function App() {
usePageTracking();
// Check User Is Logged In
useEffect(() => {
const checkLoggedIn = async () => {
// Grab Auth Token From Local Storage
let token = localStorage ? localStorage.getItem('auth-token') : window.localStorage.getItem('auth-token');
if (token === null) {
localStorage.setItem('auth-token', '');
token = '';
}
try {
// Check If Valid Token
const apiBaseUrl = config.url.API_URL;
const tokenResponse = await Axios.post(`${apiBaseUrl}/users/tokenIsValid`, null, { headers: { 'x-auth-token': token } });
// if valid token exists...
if (tokenResponse.data) {
// get the user
const userRes = await Axios.get(`${apiBaseUrl}/users/`, {
headers: { 'x-auth-token': token }
});
// Set userId for Google Analytics
ReactGA.set({ userId: userRes.data._id });
// And Set User Data, Giving User Logged-In Access
setIsUserLoading(false);
setUserData({ token, user: userRes.data });
} else {
setIsUserLoading(false);
}
} catch (err) {
setIsUserLoading(false);
}
};
checkLoggedIn();
}, []);
// render rest of the app...
// ...
}
如何修改代码来解决这些警告?由于抛出这 2 个警告,可能 React GA 没有正确设置?
如果它不是 localhost 但将 initialized
设置为 true,则您只是在初始化;
if (!window.location.href.includes('localhost')) {
ReactGA.initialize(config.gaTrackingId);
}
setInitialized(true) // for localhost we never invoked ReactGA.initialize
所以在本地主机上,没有初始化库,有一个对 ReactGA.pageview
的调用,因此应该先调用错误消息 ReactGA.initialize
。
您应该在调用 pageview
时检查 localhost
。
if (!window.location.href.includes('localhost') && initialized) {
ReactGA.pageview(location.pathname + location.search);
}