我正在尝试使用React / Gatsby和Google Analytics Reporting API v4构建一个分析仪表板。我已经从google api quickstart guide的布局组件中添加了脚本。
我知道它正在页面上加载,因为在浏览器开发人员工具控制台中,我可以访问window.gapi
,并且google登录按钮正确显示。但是在页面组件中,我有一个useEffect挂钩。装入组件后,我想使用window.gapi.client.request(...)
发出请求。
我尝试根据gatsby docs
将请求包装在if (typeof window !== undefined) { ... }
中
Layout.js
<Helmet>
<meta
name="google-signin-client_id"
content="MYCLIENTID"
/>
<meta
name="google-signin-scope"
content="https://www.googleapis.com/auth/analytics.readonly"
/>
<script src="https://apis.google.com/js/client:platform.js"></script>
</Helmet>
Index.js
useEffect(querySuccessfulSubmissions,[])
function querySuccessfulSubmissions() {
if (typeof window !== `undefined`) {
window.gapi.client
.request({
path: "/v4/reports:batchGet",root: "https://analyticsreporting.googleapis.com/",method: "POST",body: {
reportRequests: [
{
viewId: "MYVIEWID",samplingLevel: "LARGE",dateRanges: [
{
startDate: "365daysAgo",endDate: "yesterday",},],metrics: [
{
expression: `ga:goal1Completions`,alias: "",dimensions: [
{
name: "ga:yearMonth",})
.then(response => console.log('success'))
}
}
我希望可以从useEffect挂钩访问window.gapi,但我得到TypeError: window.gapi is undefined
。