You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React或Gatsby中无需window/document操作URL查询字符串

在React/Gatsby中无需访问document/window获取与设置URL查询参数的方案

针对示例URL https://link.com/?color=#fff&theme=light 的操作方法如下:

获取查询参数

Gatsby框架场景

  • 页面级组件可直接读取props自带的location属性,无需引入额外依赖:
const DemoPage = ({ location }) => {
  // 解析查询字符串
  const searchParams = new URLSearchParams(location.search)
  // 获取对应参数值
  const color = searchParams.get('color') // 返回 #fff
  const theme = searchParams.get('theme') // 返回 light

  return <div>当前主题:{theme},颜色值:{color}</div>
}
export default DemoPage
  • 普通非页面组件可使用Gatsby内置的useLocation hook获取路由信息:
import { useLocation } from 'gatsby'

const DemoComponent = () => {
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const color = searchParams.get('color')
  const theme = searchParams.get('theme')

  return <div>当前主题:{theme},颜色值:{color}</div>
}
  • 服务端渲染/服务端数据请求阶段(如getServerData)可直接从上下文读取解析完成的查询参数:
export async function getServerData(context) {
  // 无需手动解析,context.query已包含所有查询参数
  const { color, theme } = context.query
  return {
    props: { color, theme }
  }
}

// 页面组件直接从serverData中取参数即可
const DemoPage = ({ serverData }) => {
  const { color, theme } = serverData
  return <div>当前主题:{theme},颜色值:{color}</div>
}

React + React Router v6场景

直接使用框架内置的useSearchParams hook,无需手动处理location:

import { useSearchParams } from 'react-router-dom'

const DemoComponent = () => {
  const [searchParams] = useSearchParams()
  const color = searchParams.get('color') // 返回 #fff
  const theme = searchParams.get('theme') // 返回 light

  return <div>当前主题:{theme},颜色值:{color}</div>
}

设置查询参数

所有操作均使用框架封装的路由方法,避免直接操作window.location:

Gatsby框架场景

使用内置的navigate方法更新路由:

import { useLocation, navigate } from 'gatsby'

const DemoComponent = () => {
  const location = useLocation()

  const updateTheme = (newTheme) => {
    // 保留现有查询参数,仅修改需要更新的字段
    const newSearchParams = new URLSearchParams(location.search)
    newSearchParams.set('theme', newTheme)
    // 跳转新路由,replace设为true可避免新增历史记录
    navigate(`${location.pathname}?${newSearchParams.toString()}`, { replace: true })
  }

  return <button onClick={() => updateTheme('dark')}>切换为深色主题</button>
}

React + React Router v6场景

直接使用useSearchParams返回的更新方法:

import { useSearchParams } from 'react-router-dom'

const DemoComponent = () => {
  const [searchParams, setSearchParams] = useSearchParams()

  const updateTheme = (newTheme) => {
    setSearchParams(prev => {
      prev.set('theme', newTheme)
      return prev
    }, { replace: true })
  }

  return <button onClick={() => updateTheme('dark')}>切换为深色主题</button>
}

注意:如果查询参数值包含#等特殊字符,建议使用encodeURIComponent编码后再传入,URLSearchParams会自动处理编码解析逻辑,避免参数识别错误。

内容的提问来源于stack exchange,提问作者othwsav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:15:04