通过 React useState() 处理表单数据的更好方法?

IAm*_*ndy 6 typescript reactjs ionic-framework react-hooks

只是想知道是否有人有更好的解决方案来阻止我的代码中的重复?我目前正在使用它useState()来处理用户数据,并且由于存在大量不同的字段,所以它相当重复。下面是我的代码:

const [lname, setLast] = useState<string>("");
const [country, setCountry] = useState<string>("");
const [phone, setPhone] = useState<string>("");
const [email, setUsername] = useState<string>("");
const [username, setEmail] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [cpassword, setCPassword] = useState<string>("");
Run Code Online (Sandbox Code Playgroud)

表格本身(摘要):

<IonItem>
    <IonLabel position={"stacked"}>First Name</IonLabel>
    <IonInput type={"text"} value={fname} placeholder="Enter Your First Name" onIonChange={(event) => setFirst(event.detail.value ?? '')}/>
</IonItem>
Run Code Online (Sandbox Code Playgroud)

我之前在另一篇文章中看到您可以使用接口,但我不确定如何使用它来实现它,useState()或者这是否是我的代码的最佳方法,因为我然后将数据传递到 Axios POST 请求到后端被处理

    const handleRegistration = async () => {
        await axios.post('http://localhost:3000/register', {
            fname: fname,
            lname: lname,
            country: country,
            phone: phone,
            email: email,
            username: username,
            password: password,
            cpassword: cpassword
        }).then(res => {
            console.log(res);
            onRegister();
        }).catch(err => {
            console.log(err);
        });
    }
Run Code Online (Sandbox Code Playgroud)

NeE*_* TK 9

您可以在单个 useState 中处理控制数据:

import React, { useState } from "react";

const initialValues = {
        fname: "",
        lname: "",
        country: "",
        phone: "",
        email: "",
        username: "",
        password: "",
        cpassword: ""
};

export default function Form() {
  const [values, setValues] = useState(initialValues);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
  };

  return (
        <form>
          <input
            value={values.fname}
            onChange={handleInputChange}
            name="fname"
            label="fname"
          />
          <input
            value={values.lname}
            onChange={handleInputChange}
            name="lname"
            label="lname"
          />
           // ... Rest of the input fields
          <button type="submit"> Submit </button>
        </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

另外,在发送有效负载时:

const handleRegistration = async () => {
        await axios.post('http://localhost:3000/register', {
            fname: values.fname,
            lname: values.lname,
            //Rest of the input fields
        }).then(res => {
            console.log(res);
            onRegister();
        }).catch(err => {
            console.log(err);
        });
    }
Run Code Online (Sandbox Code Playgroud)


Shu*_*tri 5

您可以使用对象并提供接口,而不是对状态字段使用单独的值

interface FormState = {
  lname: string;
  country: string;
  phone: string;
  email: string;
  username: string;
  password: string;
  cpassword: string;
};
const [values, setValues] = useState<FormState>({
  lname: "",
  country: "",
  phone: "",
  email: "",
  username: "",
  password: "",
  cpassword: "",
});

const handleInputChange = (field) => (e) => {
    const val = e.detail.value;
    setValues(values => ({
      ...values,
      [field]: val,
    }));
  };


<IonItem>
    <IonLabel position={"stacked"}>First Name</IonLabel>
    <IonInput type={"text"} value={fname} placeholder="Enter Your First Name" onIonChange={handleInputChange('fname')}/>
</IonItem>
Run Code Online (Sandbox Code Playgroud)