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

如何在React中传递URL参数调用FastAPI接口获取指定数据

解决方法

你已经把用户输入的日期存到了this.state.key中,只需要修改axios请求的传参逻辑即可,推荐两种实现方式:

方式1:使用模板字符串拼接URL(简单直接)

把原来固定的URL改成ES6模板字符串,插入key变量即可:

submitHandler = e => {
    e.preventDefault()
    console.log(this.state)
    // 用模板字符串替换固定参数
    axios
        .get(`http://127.0.0.1:8000/hvals_hash?key=${this.state.key}`)
        .then(response => {
            console.log(response)
        })
        .catch(error => {
            console.log(error)
        })
}

方式2:使用axios的params配置项(更规范,自动处理特殊字符转义)

这种方式不用手动拼接URL,axios会自动把参数拼到URL上,还会自动对日期里的斜杠这类特殊符号做URL编码,避免请求出错:

submitHandler = e => {
    e.preventDefault()
    console.log(this.state)
    axios
        .get('http://127.0.0.1:8000/hvals_hash', {
          params: {
            key: this.state.key
          }
        })
        .then(response => {
            console.log(response)
        })
        .catch(error => {
            console.log(error)
        })
}

之后如果把输入框替换为日期选择器组件,只需要保证日期选择器的onChange回调把选中值赋值给state.key即可,请求逻辑不需要改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:18:03