如何使用setformdata在表单中存储数据

How to use setformdata to store data in form

我正在制作一个表格,下面是格式。如您所见,我在两种情况下(用于以多阶段形式存储)并且在我们调用 {onSubmitform} 的第二种形式上单击下一步。您可以看到的问题是,在表单中输入数据时,我面临着将其存储在何处,即 {onChange}。 另外 ~ 请让我知道这是否是 {onSubmitform} 是否可以将数据发送到后端。

import React, { useEffect, useState } from 'react';
const  Rider_Signup = ()=>{
    const [step, setstep] = useState(1);
    const [formdata, setFormData] = useState({zipcode:"", email:"",name:"",location:"", dob:"",phone:"",sex:"", password:"",aadhar:""}); // use to hold input from user 
    const onSubmitform = async e =>{
        e.preventDefault();
        try{
 
            const email=formdata.email;
            console.log(email);

            const body={email};

            const response = await fetch("http://localhost:5000/api/service/signup",{
                method:"POST",headers:{"Content-Type":"application/json"},
                body:JSON.stringify(body)
            })
            const datainjson = await response.json();

            window.location =`/driver/login`;

        }catch(err){
            console.log('Error')
        }

    }
    const renderForm = () =>{
    switch(step){
        case 1: return <div className="admin_form_div">
        <h1 className="form_header">Hey ! </h1>
    
        <center>
            <form  action="/initial" id="admin_form"  name="admin_form">
                <label for="Email" className="label">Enter the Email</label><br/>
                <input type="email" name="name" className="Email" value={formdata.email} onChange={e =>{console.log(formdata.email)
                    setFormData(formdata.email=(e.target.value))}} placeholder="email@id.com" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="Please enter valid email" required />
                <br/>
                <br/>


                <button onClick = {() => setstep(step+1)}>Submit</button>

        </form> 
        </center>




    </div>
        case 2: return <div><h1>{formdata.email} </h1><button onClick = {() => setstep(step+1)}>Submit</button></div>
        default: return <div> {onSubmitform}</div>


    }

}
return (

    renderForm()
)
  
};
 
export default Rider_Signup;
  • formdata 是 const 并且无法重新分配,
  • 只能使用 setFormData 挂钩更改表单数据。
  • ...formdata 将在仅更改电子邮件时保存其他字段。
  • 此外,这是重复的。
onChange={
    e => {
        console.log(formdata.email)
        setFormData({ ...formdata, email: e.target.value })
    }
}