在 Nextjs 中,如何提取位置栏中的内容?

In Nextjs, how to extract what's in the location bar?

我正在关注 this guide to learn how to implement a Login with Google button (along with the help of Strapi。该指南适用于 Reactjs。

当我尝试用这部分代码对 Nextjs 做同样的事情时,出现了 问题

import React, { useState, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import axios from 'axios'

function GoogleAuthCallback() {
  const [auth, setAuth] = useState()
  const location = useLocation()
  useEffect(() => {
    if (!location) {
      return
    }
    const { search } = location
    axios({
      method: 'GET',
      url: `http://localhost:1337/auth/google/callback?${search}`,
    })
      .then((res) => res.data)
      .then(setAuth)
  }, [location])

  return (
    <div>
      {auth && (
        <>
          <div>Jwt: {auth.jwt}</div>
          <div>User Id: {auth.user.id}</div>
          <div>Provider: {auth.user.provider}</div>
        </>
      )}
    </div>
  )
}

export default GoogleAuthCallback

我收到以下错误:

**问题:有没有办法提取 Nextjs 中地址栏中的内容,因为 useLocation() 不起作用。

谢谢!

我猜 useLocation() 试图访问 window.location,这在 SSR 中没有定义。 您应该在禁用 SSR 的情况下动态导入您的组件: 例如在您的页面中:

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/GoogleAuthCallback'), // <- path of your component
  { ssr: false } 
) 

请注意,您也可以使用默认 next.js router :

import { useRouter } from 'next/router'
function GoogleAuthCallback() {
  const [auth, setAuth] = useState()
   const router = useRouter()
   const location = router.pathname // or router.asPath
  ....
}

答案很简单,你必须使用路由器而不是位置来更新你的组件,例如:

import {useRouter} from "next/router"
const router = useRouter();
useEffect(() => {'something happened here'},[router])