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

React项目中如何提取登录邮箱前缀作为参数传给API

解决方案

axios 的 GET 请求查询参数需要放在第二个配置项的 params 字段中,你已经完成了用户名提取逻辑,仅需要调整请求传参格式即可,具体修改如下:

修改要点

  • 原代码直接将表单values作为axios.get的第二个参数传入,不符合GET请求传参规范
  • 仅需将提取到的username作为name参数传递,无需提交密码等其他多余字段
  • 建议将setSubmitting(false)放到请求完成/失败的回调中,避免请求还在响应时就提前重置提交状态

修改后的完整代码

export const loginUser = (values, history, setFieldError, setSubmitting) => {
    console.log("values from login", values)

    // 拆分邮箱提取用户名
    const username = values.email.split("@")[0]
    console.log("user name", username)

    return () => {
        axios.get('https://api.agify.io/', {
          // 查询参数统一放在params字段中,axios会自动拼接为url query
          params: {
            name: username
          }
        }).then((response) => {
            console.log("response", response)
            // 响应正常时跳转
            history.push("/user")
        }).catch(error => {
            console.error(error)
            // 可在这里添加错误提示逻辑
        }).finally(() => {
            // 无论请求成功失败都重置提交状态
            setSubmitting(false);
        })
    }
}

修改后请求会自动拼接为 https://api.agify.io/?name=你的用户名,符合API的传参要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:04