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

React函数组件提取URL参数作为props发起axios请求的方法

问题根因

代码运行异常来自两处错误:

  • 函数组件没有类组件的this实例,使用this.props取值只会得到undefined
  • 未对URL中的查询参数做解析,直接读取props上的customer、date属性无法拿到目标值
修复步骤
  1. 提取URL中的查询参数
  • 若项目使用React Router v6,直接用官方Hook取参:
import { useSearchParams } from 'react-router-dom'

// 在函数组件顶层调用
const [searchParams] = useSearchParams()
const customer = searchParams.get('customer')
const date = searchParams.get('date')
  • 若未使用路由库,用原生URL API即可解析:
const urlParams = new URLSearchParams(window.location.search)
const customer = urlParams.get('customer')
const date = urlParams.get('date')

针对示例地址http://localhost:3000/update?customer=66&date=2022-06-27&tab=user,上述代码解析后得到的customer值为"66",date值为"2022-06-27"。

  1. 修正请求函数的写法
    去掉函数中错误的this引用,直接把解析到的参数传入函数即可,修正后的代码如下:
const getData = async (customer, date) => {
  const config = {
    headers: {
      Authorization: `token ${localStorage.getItem("token")}`,
    },
  }
  try {
    const res = await axios.get(`api?customer=${customer}&date=${date}`, config)
    return res.data
  } catch (err) {
    console.error("error ocurred while fetching data", err)
    return null
  }
}

提示:URL解析出的参数默认是字符串类型,如果接口要求customer为数字类型,传参前可通过Number(customer)做类型转换。

  1. 组件内调用示例
    在函数组件的副作用钩子中,等参数解析完成后调用请求即可:
import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'

function UpdatePage() {
  const [searchParams] = useSearchParams()
  const [pageData, setPageData] = useState(null)

  useEffect(() => {
    const customer = searchParams.get('customer')
    const date = searchParams.get('date')
    if (customer && date) {
      getData(customer, date).then(data => setPageData(data))
    }
  }, [searchParams])

  return <div>{/* 页面业务逻辑 */}</div>
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:57:20