在哪里放置组件确实安装在我的 next.js 文件中

9 google-analytics reactjs next.js

哈喽,伙计们,很抱歉这个愚蠢的问题,但是我应该将 componentDidMount() 放在我的 React js 文档中的哪里?

我正在尝试插入谷歌分析脚本,我在上面找到了一个视频,但我不知道将该元素放在哪里。我会给你我的文件的屏幕截图。

谢谢(我知道我的编辑器很奇怪,但 Visual Studio 代码总是崩溃)

在此输入图像描述

在此输入图像描述

UNl*_*nel 9

嘿,看来你找到了答案,但这是我的看法,也许对其他人有帮助。

componentDidMount只能在类组件中工作。从图中可以看出,About 是功能组件。

在这种情况下,React.useEffect 相当于函数组件中的 componentDidMount。它可用于调用 init (或执行任何其他副作用)

 const About = () => {
    
    React.useEffect(() => {
    
     ReactGA.init()
    
    }, [])
    
    //rest of the component
return ( 

<section> .... </section>

)

    
}
Run Code Online (Sandbox Code Playgroud)

您可能需要考虑的一点是使用 _app.js 组件。

这是下一个 js 基本组件,它包装了所有页面,因此所有页面中使用的任何逻辑或布局都可以插入其中。

function MyApp({ Component, pageProps }) {
  React.useEffect(() => {
    ReactGA.init()
  }, [])
  return (
    <div>
      <Header />
      <Component {...pageProps} />
      <Footer />
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

这只会在组件安装上运行,好处是应用程序不会再在任何其他组件安装上加载它,并且可以通过应用程序访问 api。


ElD*_*n90 5

您可能想创建一个布局组件

例子:

// components/layout.js
import React from 'react'
import { initGA, logPageView } from '../utils/analytics'

export default class Layout extends React.Component {
  componentDidMount () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }
  render () {
    return (
      <div>
        {this.props.children}
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用Layout来包裹其他组件

例子:

// pages/about.js
import Layout from '../components/layout'

export default () => (
  <Layout>
    <div>About us</div>
  </Layout>
)
Run Code Online (Sandbox Code Playgroud)

例子:

// utils/analytics.js
import ReactGA from 'react-ga'

export const initGA = () => {
  console.log('GA init')
  ReactGA.initialize('UA-xxxxxxxxx-1')
}
export const logPageView = () => {
  console.log(`Logging pageview for ${window.location.pathname}`)
  ReactGA.set({ page: window.location.pathname })
  ReactGA.pageview(window.location.pathname)
}
export const logEvent = (category = '', action = '') => {
  if (category && action) {
    ReactGA.event({ category, action })
  }
}
export const logException = (description = '', fatal = false) => {
  if (description) {
    ReactGA.exception({ description, fatal })
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。