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

React表单提交API时输入值显示undefined问题求助

问题:React表单提交值为undefined的排查与解决

我正在使用React、JS及基础HTML开发一个简易表单提交应用,需将表单提交结果以POST请求发送至API。目前遇到的问题是:每次提交均能连接API并返回200状态码,但表单输入的值显示为undefined。我怀疑这与代码中的handleSubmit函数有关,但无法明确如何正确传递表单数据。

原代码示例

class Form extends React.Component {
  constructor(props) {
    super(props);

    // declare input fields in state
    this.state = { value: "" };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  // handle change events
  handleChange = (event) => {
    this.setState({
      value: event.target.value,
    });
  };

  // handle submission events
  handleSubmit = (events) => {
    const username = "- username -";
    const password = "- password - ";

    let data = `${username}:${password}`;
    let encodedString = btoa(data);
    let proxyLink = "- proxy URL -";
    let URL = "- endpoint URL -";
    let proxyURL = proxyLink + URL;

    const options = {
      method: "POST",
      body: JSON.stringify(this.state),
      headers: {
        accept: "application/json",
        authorization: `Basic ${encodedString}`,
      },
    };

    fetch(proxyURL, options)
      .then((response) => response.json())
      .then((response) => console.log(response))
      .catch((err) => console.error(err));
    events.preventDefault();
  };

  render() {
    const { values } = this.state;
    return (
      <form onSubmit={this.handleSubmit}>
        <div>
          <label>value: </label>
          <input
            type="text"
            value={attibute_name}
            onChange={this.handleChange}
            name="attribute_name"
          />
        </div>
      </form>
    );
  }
}

export default Form;

我尝试过调整handleSubmit的使用方式,甚至将其定义为变量并改为异步函数,参考相关教程后效果反而更差。


问题分析与修复方案

你的代码里有几个明显错误导致表单值无法正确传递:

  • Input的value属性绑定错误:你写的value={attibute_name}是未定义变量,且拼写错误(attibute应为attribute),正确写法是绑定到state中的value字段:value={this.state.value}。
  • 冗余的state解构:render里const { values } = this.state;完全多余,state里只有value字段,且该变量未被使用,直接删除即可。
  • 事件处理细节问题:handleSubmit的参数名写成events(规范应为event);event.preventDefault()应该放在fetch请求之前,避免页面提前刷新中断请求。
  • 方法绑定冗余:箭头函数定义的handleChange和handleSubmit会自动绑定this,不需要在constructor里手动绑定,可删除对应绑定代码。

修复后的完整代码

class Form extends React.Component {
  constructor(props) {
    super(props);
    // declare input fields in state
    this.state = { value: "" };
  }

  // handle change events
  handleChange = (event) => {
    this.setState({
      value: event.target.value,
    });
  };

  // handle submission events
  handleSubmit = (event) => {
    event.preventDefault(); // 提前阻止默认行为,避免页面刷新

    const username = "- username -";
    const password = "- password - ";

    let data = `${username}:${password}`;
    let encodedString = btoa(data);
    let proxyLink = "- proxy URL -";
    let URL = "- endpoint URL -";
    let proxyURL = proxyLink + URL;

    const options = {
      method: "POST",
      body: JSON.stringify(this.state),
      headers: {
        accept: "application/json",
        authorization: `Basic ${encodedString}`,
        "Content-Type": "application/json" // 明确告知API请求体格式
      },
    };

    fetch(proxyURL, options)
      .then((response) => response.json())
      .then((response) => console.log(response))
      .catch((err) => console.error(err));
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div>
          <label>value: </label>
          <input
            type="text"
            value={this.state.value}
            onChange={this.handleChange}
            name="attribute_name"
          />
        </div>
        <button type="submit">提交</button> {/* 添加提交按钮,方便用户触发提交 */}
      </form>
    );
  }
}

export default Form;

额外补充两个实用建议:

  1. 给表单添加提交按钮,否则用户无法通过点击操作触发提交;
  2. 在请求header中添加"Content-Type": "application/json",明确告知API请求体为JSON格式,避免部分API解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:40:20