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

React页面开发求助:从PHP接口取数据并提交至另一PHP页面

问题解决:React整合数据展示与提交功能

代码中的核心问题

  • state命名错误:定义的client数组,渲染时误写为cliente,导致数据无法渲染
  • 表单状态管理失效:handleInputChange仅更新单个name字段,无法追踪多输入框的变化
  • 提交数据未定义:直接使用未声明的formData变量,无法收集用户修改后的内容
  • state结构不合理:仅用数组存储原始数据,无法实时维护用户编辑后的表单值

修正后的完整代码

import React, { Component } from 'react';
import axios from 'axios';

class ClientUpdate extends Component 
{
    state = {
      clients: [], // 存储所有从后端获取的客户数据
      currentClient: {} // 实时维护当前编辑的客户表单数据
    }
    
    componentDidMount() 
    {
      const url = 'http://localhost:8888/select_client.php'
      axios.get(url)
        .then(response => {
          this.setState({ 
            clients: response.data,
            // 默认加载第一条客户数据到编辑状态
            currentClient: response.data[0] || {} 
          });
        })
        .catch(error => console.error('数据加载失败:', error));
    }
       
    handleInputChange = (event) => 
    {
      const { name, value } = event.target;
      // 根据输入框name属性动态更新对应字段
      this.setState(prevState => ({
        currentClient: {
          ...prevState.currentClient,
          [name]: value
        }
      }));
    };
      
    handleSubmit = (event) => 
    {
      event.preventDefault();
      
      // 直接使用维护好的currentClient作为提交数据
      const formData = this.state.currentClient;
      
      axios
        .post("http://localhost:8888/update_client.php", formData)
        .then((response) => 
        {
          console.log('更新成功:', response);
          // 提交成功后重新拉取数据,更新页面
          this.componentDidMount();
        })
        .catch((error) => 
        {
          console.error('更新失败:', error);
        });
    };
      
    render() 
    {
      const { clients, currentClient } = this.state;
      return (
        <div className="container-fluid d-flex justify-content-center">
          {clients.length === 0 ? (
            <p>加载中...</p>
          ) : (
            <form className="form-group" onSubmit={this.handleSubmit}>
              <h1 className="mt-4 d-flex justify-content-center">UPDATE</h1>
              <input 
                type="hidden" 
                className="form-control" 
                name="Id_cliente" 
                value={currentClient.Id_cliente || ''} 
                onChange={this.handleInputChange}
              />
              <div>
                <label htmlFor="username">Username:</label>
                <input 
                  type="text" 
                  className="form-control" 
                  name="Username" 
                  id="username" 
                  placeholder="请输入用户名" 
                  autoComplete="on" 
                  value={currentClient.Username || ''} 
                  onChange={this.handleInputChange} 
                />
              </div>
              <div>
                <label htmlFor="email">Email:</label>
                <input 
                  type="email" 
                  className="form-control" 
                  name="Email" 
                  id="email" 
                  placeholder="请输入邮箱" 
                  autoComplete="on" 
                  value={currentClient.Email || ''} 
                  onChange={this.handleInputChange} 
                />
              </div>
              <div>
                <label htmlFor="password">Password:</label>
                <input 
                  type="password" 
                  className="form-control" 
                  name="Password" 
                  id="password" 
                  autoComplete="off" 
                  value={currentClient.Password || ''} 
                  onChange={this.handleInputChange} 
                />
              </div>

              <button type="submit" className="btn btn-primary btn-lg w-100 mt-3">Submit</button>
            </form>
          )}
        </div>
      );
    }
}

export default ClientUpdate;

关键修改说明

  1. 优化state结构:拆分出clients(存储原始数据)和currentClient(维护编辑状态),解决状态追踪问题
  2. 动态表单更新:通过输入框的name属性匹配currentClient的字段,实现单个方法处理所有输入框变化
  3. 完善数据提交逻辑:直接使用currentClient作为提交数据,确保提交内容与用户编辑一致,同时添加提交成功后的数据刷新
  4. 增强用户体验:添加加载状态提示和错误捕获,避免页面空白或无反馈

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:40:31