小编SHA*_*OOZ的帖子

如何在 next.js 应用程序中使用谷歌分析?

我在 next.js 中使用 styled-components,所以我的样式需要在服务器端呈现,因此我如何将谷歌分析添加到我的网站?

我检查了next.js 谷歌分析示例,但正如我所说,由于使用了样式组件,我的 _document 文件有所不同。

// _document.js

import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () => originalRenderPage({
        enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
      })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal() …
Run Code Online (Sandbox Code Playgroud)

javascript google-analytics reactjs styled-components next.js

46
推荐指数
6
解决办法
4万
查看次数

Next.JS:如何处理 getInitialProps 中的错误?

我想从 API 获取数据,如果失败,我希望它呈现_error.js页面。我的请求取决于路由器查询。因此,如果用户输入错误的查询,页面将引发错误。

如果请求因抛出而失败,我希望_error.js显示我的自定义。

我如何实现这一目标?

这是我的索引页:

// pages/index.js

import React from 'react'
import PropTypes from 'prop-types'
import fetch from 'isomorphic-unfetch'
import Items from '../components/Items'
import { API } from '../utils/config'

const IndexPage = ({ items }) => {
  return (
    <div>
      <Items items={items} />
    </div>
  )
}

IndexPage.getInitialProps = async (context) => {
  const { query } = context
  const filter = query.filter || ''
  const name = query.name || ''
  const page = query.page || …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs next.js

5
推荐指数
1
解决办法
8775
查看次数