IT이야기

Resact useState()를 통해 양식 데이터를 처리하는 더 나은 방법?

cyworld 2022. 3. 29. 21:42
반응형

Resact useState()를 통해 양식 데이터를 처리하는 더 나은 방법?

내 코드의 반복을 멈추게 할 더 좋은 해결책이 있는지 궁금해서?나는 현재 사용하고 있다.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>("");

양식 자체(요약):

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

이전에 다른 게시물에서 인터페이스를 사용할 수 있다는 것을 보았지만, 어떻게 이 인터페이스를 구현할 수 있을지는 확실하지 않다.useState()또는 내가 처리될 Axios POST 요청을 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);
        });
    }

단일 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>
  );
}

또한 페이로드 전송 시:

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);
        });
    }

상태 필드에 개별 값을 사용하는 대신 개체를 사용하고 인터페이스를 제공할 수 있음

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>
import React, { useState } from 'react';

const Form = () => {
  const [inputValues, setInputValues] = useState<{ [x: string]: string }>()

  const handleFormSubmit = async (e: React.MouseEvent<HTMLElement>) => {
    e.preventDefault()
    const data = {
      name: inputValues?.name,
      email: inputValues?.email,
      phone: inputValues?.phone,
      income: inputValues?.name
    }

    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    };

    try {
      const response = await fetch('https://xyz/form-submit', requestOptions)
      const res = await response.json()
      console.log(res)
    } catch (error) {
      console.log(error)
    }
  }

  const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
    const { name, value } = e.currentTarget
    setInputValues(prevState => ({ ...prevState, [name]: value }))
  }

  return (
    <div className="Form">
      <div className="form-wrapper">
        <h1>Demo Form for React</h1>
        <form className="form">
          <input 
            className="form-input"
            name="name" 
            value={inputValues?.name || ''} 
            onChange={handleInputChange} 
            placeholder="Your Name"
            type="text"
            data-testid="form-input-name"
          />
          <input 
            className="form-input"
            name="phone" 
            value={inputValues?.phone || ''} 
            onChange={handleInputChange} 
            placeholder="Your Phone" 
            type="tel"
            data-testid="form-input-phone"
          />
          <input 
            className="form-input" 
            name="email"
            value={inputValues?.email || ''} 
            onChange={handleInputChange} 
            placeholder="Your Email" 
            type="email"
            data-testid="form-input-email"
          />
          <input 
            className="form-input"
            name="income"
            value={inputValues?.income || ''} 
            onChange={handleInputChange} 
            placeholder="Your Annual Income" 
            type="number"
            data-testid="form-input-income"
          />
          <button 
            className='form-submit'
            data-testid="form-submit" 
            onClick={handleFormSubmit}
          >
            Submit
          </button>
        </form>
      </div>
    </div>
  );
}

export default Form;

샘플 유형첨자 양식.특징:

  • 싱글onChange핸들러
  • 형식적인 컴파일러가 우리에게 소리치지 않아도 우리가 많은 핵심 가치 쌍을 추가할 수 있는 하나의 상태 객체.
  • ES2020 선택 체인을 사용한다.
  • 몇 가지 장치 테스트를 실행하려는 DOM 요소에 데이터 테스트가 있음.
  • 입력 필드의 유형에 따라 자동 완성 기능을 제공해야 한다.
  • Form Submit function sample을 from call to end point에 가져오기 위해 petch api를 사용하는 기능 샘플.

마음 내키는 대로 쓰세요.

p.s: 대부분 그것의 종류.그러나, 당신은 언제나 제네릭을 사용하여 국가 오브젝트에 대한 무감각을 더할 수 있다.

참조URL: https://stackoverflow.com/questions/66692085/better-way-of-handling-form-data-via-react-usestate

반응형