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

React动态输入框的firstName/lastName值如何存入SQL数据库?

如何获取React动态输入框的值并存入SQL数据库

你已经完成了动态输入字段的实现,其实所有输入框的firstName和lastName值已经实时保存在inputList这个状态数组里了——页面底部的JSON.stringify(inputList)也能直观看到所有数据。接下来只需要把这个数组发送给后端,由后端完成SQL数据库的写入操作即可,具体步骤如下:

1. 前端添加提交逻辑

在组件里新增提交按钮和提交函数,把inputList的数据通过HTTP请求发送到后端接口:

修改后的完整代码:

import React, { useState } from "react";

function App() {
  const [inputList, setInputList] = useState([{ firstName: "", lastName: "" }]);

  const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...inputList];
    list[index][name] = value;
    setInputList(list);
  };

  const handleAddClick = () => {
    setInputList([...inputList, { firstName: "", lastName: "" }]);
  };

  // 新增提交函数,发送数据到后端
  const handleSubmit = async () => {
    // 可选:过滤掉空输入项,避免存入无效数据
    const validData = inputList.filter(item => item.firstName.trim() || item.lastName.trim());
    if (validData.length === 0) {
      alert("请输入至少一条有效数据");
      return;
    }

    try {
      // 替换成你的后端API地址,比如http://localhost:3001/api/save-names
      const response = await fetch("/api/save-names", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(validData),
      });

      if (response.ok) {
        alert("数据保存成功");
        // 保存成功后重置输入列表(可选)
        setInputList([{ firstName: "", lastName: "" }]);
      } else {
        alert("数据保存失败,请稍后重试");
      }
    } catch (error) {
      console.error("请求出错:", error);
      alert("网络请求出错,请检查后端服务是否运行");
    }
  };

  return (
    <div className="App">
      {inputList.map((x, i) => {
        return (
          <div className="box" key={i}> {/* 必须添加key属性,React列表渲染要求 */}
            <input
              name="firstName"
              placeholder="输入名字"
              value={x.firstName}
              onChange={e => handleInputChange(e, i)}
            />
            <input
              className="ml10"
              name="lastName"
              placeholder="输入姓氏"
              value={x.lastName}
              onChange={e => handleInputChange(e, i)}
            />
            <div className="btn-box">
              {inputList.length - 1 === i && <button onClick={handleAddClick}>添加</button>}
            </div>
          </div>
        );
      })}
      {/* 新增提交按钮 */}
      <button onClick={handleSubmit} style={{ marginTop: 20, padding: '8px 16px' }}>保存到数据库</button>
      <div style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
    </div>
  );
}

export default App;

2. 后端编写接口处理SQL插入

前端无法直接操作SQL数据库,必须通过后端接口来完成。以下是Node.js + Express + MySQL的示例(其他后端语言逻辑类似):

const express = require('express');
const mysql = require('mysql2');
const app = express();

// 解析JSON格式的请求体
app.use(express.json());

// 配置数据库连接,替换成你的数据库信息
const db = mysql.createConnection({
  host: 'localhost',
  user: '你的数据库用户名',
  password: '你的数据库密码',
  database: '你的数据库名'
});

// 连接数据库
db.connect(err => {
  if (err) throw err;
  console.log('数据库连接成功');
});

// 处理前端的保存请求
app.post('/api/save-names', (req, res) => {
  const nameList = req.body;
  
  // 验证数据格式
  if (!Array.isArray(nameList) || nameList.length === 0) {
    return res.status(400).send('请传入有效的数据列表');
  }

  // 批量插入数据到SQL表(假设表名为users,包含firstName和lastName字段)
  const insertSql = 'INSERT INTO users (firstName, lastName) VALUES ?';
  const insertValues = nameList.map(item => [item.firstName, item.lastName]);

  db.query(insertSql, [insertValues], (err, result) => {
    if (err) {
      console.error('插入数据失败:', err);
      return res.status(500).send('数据保存失败');
    }
    res.status(200).send(`成功保存 ${result.affectedRows} 条数据`);
  });
});

// 启动后端服务,端口号3001
app.listen(3001, () => {
  console.log('后端服务运行在 http://localhost:3001');
});

关键注意事项

  • 确保后端服务和前端服务跨域问题已处理(可以用CORS中间件,比如cors包)
  • 数据库表需要提前创建,比如users表包含firstName和lastName字段
  • 生产环境要做好数据验证和错误处理,避免SQL注入风险(上面的示例已使用参数化查询,规避了注入风险)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:35:36