在Next.js中如何获取地址栏内容?react-router-dom的useLocation无法使用
问题原因
你遇到的报错是因为Next.js采用自研路由系统,并不支持react-router-dom的相关钩子,useLocation是react-router-dom专属的能力,所以在Next.js中调用会返回undefined,最终触发属性读取报错。
解决方案
你可以用Next.js内置的路由能力直接获取地址栏参数,以下是不同路由模式下的修改方案:
1. Pages Router 模式适用代码
import React, { useState, useEffect } from 'react' import { useRouter } from 'next/router' import axios from 'axios' function GoogleAuthCallback() { const [auth, setAuth] = useState() const router = useRouter() useEffect(() => { // 等待路由初始化完成再读取参数 if (!router.isReady) return // 直接获取地址栏完整查询字符串 const search = window.location.search axios({ method: 'GET', url: `http://localhost:1337/auth/google/callback${search}`, }) .then((res) => res.data) .then(setAuth) }, [router.isReady]) 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
2. App Router 模式适用代码(Next.js 13+)
需要在文件顶部添加客户端组件标识,使用useSearchParams获取查询参数:
'use client' import React, { useState, useEffect } from 'react' import { useSearchParams } from 'next/navigation' import axios from 'axios' function GoogleAuthCallback() { const [auth, setAuth] = useState() const searchParams = useSearchParams() useEffect(() => { if (!searchParams) return // 直接拼接查询字符串 axios({ method: 'GET', url: `http://localhost:1337/auth/google/callback?${searchParams.toString()}`, }) .then((res) => res.data) .then(setAuth) }, [searchParams]) 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
如果你不需要适配服务端渲染逻辑,也可以直接用浏览器原生APIwindow.location.search读取地址栏查询参数,不需要引入任何路由相关钩子。
内容的提问来源于stack exchange,提问作者Bassam
相关产品推荐
相关产品推荐

