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

Where to put component did mount in my next.js file

各位好,很抱歉提出这个愚蠢的问题,但是我应该将 componentDidMount() 放在我的 React js 文档中的什么位置?

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

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

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

示例:

// 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>
    )
  }
}

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

示例:

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

export default () => (
  <Layout>
    <div>About us</div>
  </Layout>
)

示例:

// 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 })
  }
}

希望对您有所帮助。

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

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

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

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

<section> .... </section>

)

    
}

您可能要考虑的一点注意事项是使用 _app.js 组件。

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

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

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