我想在 React.js 和 Mysql 的表单列(自动填充数据)中显示从 api 获取的数据

I want to display fetched data from api in form columns (auto fill data) in React.js and Mysql

我正在使用 onKeyUp 事件触发 api,但没有提交表单,如果手机号码匹配,我成功获取了响应数据。但我不明白如何将这些数据显示为列中的默认值。我也尝试在 useState 默认值中执行此操作,但它不起作用。

请帮帮我。谢谢!

这是我的前端代码。

import React, { useEffect, useState } from 'react'
import { Alert } from 'react-bootstrap';
import { useForm } from 'react-hook-form';

const Billing = () => {

    const [fill, setFill] = useState(false);
    const [success, setSuccess] = useState(false);
    const [customerDataFill, setCustomerDataFill] = useState()
  
    const {
      register,
      handleSubmit,
      formState: { errors },
    } = useForm();

   

    const [bill, setBill] = useState({
      contactNo: "",
     
    });

    const OnKeyUpFunc = () =>{
      const { contactNo } = bill; 
  
          axios.post("http://localhost:5000/getCustomerDetails", {
            contactNo: contactNo,
          })
          .then((Rres) => {
            setCustomerDataFill(Rres.data)
            console.log(Rres.data, "<<<<-----This is customer details testing...");
          }); 
      }


//**I WANT TO DISPLAY THIS FETCHED CUSTOMER NAME IN CUSTOMER NAME COLUMN**

      const GetCustNameFill = customerDataFill && customerDataFill.map((cData) => cData.Cust_Name)


      const [customerName, setcustomerName] = useState("")
      console.log(GetCustNameFill,"----<><><> GetCustNameFill fetch name checking")

    const handleCustNameChange = (e) => {
      setcustomerName(e.target.value);
      // console.log(e, "this is e check...");
    };

    let name, value;
    const handleInputs = (e) => {
      console.log(e);
      name = e.target.name;
      value = e.target.value;
  
      setBill({ ...bill, [name]: value });
      setFill(false);
    };
  
    const onclick = async (e) => {
      // e.preventDefault();
      const {  contactNo  } =
        bill;
  
      try {
        if (
            customerName === "" ||
            contactNo === "" 
            
        ) {
          setFill(true);
          setSuccess(false);
        } else {
          setFill(false);
          const config = {
            header: {
              "Content type": "appication/json",
            },
          };
  
          const { data } = await axios.post(
            "http://localhost:5000/billing_data",
            {   
              cust_name : customerName,
              contact_no : contactNo,
             
            },
            config
          );
  
          console.log(data);
          localStorage.setItem("Billing_details", JSON.stringify(data));
          setSuccess(true);
        }
      } catch (error) {
        console.log(error);
      }
    };

return ( <>

    <div className="modal fade" id="modalCenter" tabindex="-1" aria-hidden="true">
                          <div className="modal-dialog modal-dialog-centered modal-lg" role="document">
                            <div className="modal-content">
                              <div className="modal-header">
                                <h5 className="modal-title" id="modalCenterTitle">Bill information</h5>
                                <button
                                  type="button"
                                  className="btn-close"
                                  data-bs-dismiss="modal"
                                  aria-label="Close"
                                ></button>
                              </div>

                              <form onSubmit={handleSubmit(onclick)} method="POST">
                  {fill && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong > Please Fill All the Required Field!</strong>
                      </Alert>
                    </div>
                  )}

                  {success && (
                    <div className="container mt-3">
                       <Alert variant="success" style={{ fontSize: 15 }}>
                        <strong style={{color:"green"}}>Bill Added Successssfully!</strong>
                      </Alert>
                    </div>
                  )}

                  {errors.contact && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong>{errors.contact.message}</strong>
                      </Alert>
                    </div>
                  )}
                  
                  {errors.email && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong>{errors.email.message}</strong>
                      </Alert>
                    </div>
                  )}
                              <div className="modal-body">
                              <div className="row  g-2">
                              <div className="col mb-2">
                                    <label for="nameWithTitle" className="form-label">Contact No.</label>
                                    <input
                                      type="text"
                                      id="nameWithTitle"
                                      className="form-control"
                                      placeholder="Enter Contact no."
                                      value={bill.contactNo}
                                      onChange={handleInputs}
                                      name="contactNo"
                                      onKeyUp={OnKeyUpFunc}
                                    />
                                  </div>

                              <div className="col mb-2">
                                    <label for="emailWithTitle" className="form-label">Customer name</label>
                                    <input
                                      type="text"
                                      id="emailWithTitle"
                                      className="form-control"
                                      placeholder="Enter Customer Name"
                                      value={customerName}
                                      onChange={handleCustNameChange}
                                      defaultValue={GetCustNameFill}
                                    />
                                  </div>

                                 
                                </div>

                               


                              </div>
                              <div className="modal-footer">
                                <button type="button" className="btn btn-outline-secondary" data-bs-dismiss="modal">
                                  Close
                                </button>
                                <button type="submit" className="btn btn-primary">submit</button>
                              </div>
                             </form>
                            </div>
                          </div>
                        </div>
  </>
  )
}

export default Billing

** 这是后端代码**

var express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mysql = require("mysql");
const expressAsyncHandler = require("express-async-handler");
const generateToken = require("./jwtToken/generateToken");
const bcrypt = require("bcryptjs");

const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "star_battery_db",
});

db.connect((err) => {
  if (err) {
    console.warn("Error in connection, Check XAMPP server");
  } else {
    console.warn("MySql db connected");
  }
});

app.use(cors());
app.use(express.json()); 
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(5000, () => console.log("Server is running on 5000"));

// Api for fetch Partcular customer data for billing.
app.post("/getCustomerDetails",expressAsyncHandler(async (req, res) => {
  const contactNo = req.body.contactNo

  const users = `SELECT * FROM cust_master WHERE Contact= ${db.escape(contactNo)}`;
  db.query(users, (err, result) => {
    if (err) {
      res.status(404).send(err);
    }
    res.status(201).send(result);
  });
})
); ```

您是直接在输入的默认值内发送数组。输入的默认值需要文本。
如果要通过api更新defaultValue,下面是流程

注释行 const GetCustNameFill 和 console.log GetCustNameFill
在 onKeyUp 函数内部使用 setCustomerDataFill(Rres.data[0]);

并将输入默认值变量从 GetCustNameFill 更改为 customerDataFilldefaultValue={customerDataFill.Cust_Name}

我认为您不需要 customerDataFill 状态。
使用 customerName 状态应该足够了。
如果找到带有 contactNocustomerName 未设置的 user,请更改您的 OnKeyUpFunc 以设置 customerName

const [customerName, setcustomerName] = useState('');

const OnKeyUpFunc = () => {
  const { contactNo } = bill;

  axios
    .post('http://localhost:5000/getCustomerDetails', {
      contactNo: contactNo,
    })
    .then(({ data }) => {
      // If at least a user with `contactNo` has been found, set `customerName`
      if (data.length) {
        setcustomerName(data[0].Cust_Name);
      }
    });
};

最后,只保留emailWithTitle输入中的value

<div className="col mb-2">
  <label for="emailWithTitle" className="form-label">Customer name</label>
  <input
    type="text"
    id="emailWithTitle"
    className="form-control"
    placeholder="Enter Customer Name"
    value="{customerName}"
    onChange="{handleCustNameChange}"
  />
</div>

当您更改 nameWithTitle 值且 emailWithTitle 尚未设置时,这应该作为自动完成。