들어가기전에..
- React는 본인의 state가 변경될 때 리렌더링이 된다.
특히 input같은경우는 변경 사항이 많고, 변경이 있을때 마다 useState로 리렌더링 되는 문제를 최적화하고 싶었다.
- FormData를 사용해서 input값을 가져와서 onSubmit할때 사용했다.
- 아래 요소에서도 그렇고 "email"등 공통으로 사용하고 있어서, 만약 name="" 속성에 적어줘야 하는 값이 달라지면, 즉 form 요소의 name을 변경해야 하면 따라다니며 수정해야 할거 같아 이 부분도 수정하였다.
이전 코드..
const [pSignForm, setpSignForms] = useState({
email: "",
password: "",
name: "",
address: "",
});
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const { email, password, name, address } = pSignForm;
if (!email || !password || !name || !address || !businessImg || !pharmImg) {
return alert("모든 항목을 입력해주세요");
}
if (error.email === true || error.password === true || error.name === true) {
return alert("항목을 다시 확인해주세요");
}
if (checks === false) {
return alert("회원가입시, 사용자의 현재 위치를 사용하는 것에 동의해주세요");
}
};
최적화한 코드..
const [pSignForm, setpSignForms] = useState({
email: "",
password: "",
name: "",
address: "",
});
const FORM_FIELD_NAMES = {
EMAIL: "email",
PASSWORD: "password",
NAME: "name",
ADDRESS: "address",
};
const onSubmit: any = (e: { preventDefault: () => void; target: HTMLFormElement | undefined }) => {
e.preventDefault();
const formData = new FormData(e.target);
const email = formData.get(FORM_FIELD_NAMES.EMAIL);
const password = formData.get(FORM_FIELD_NAMES.PASSWORD);
const name = formData.get(FORM_FIELD_NAMES.NAME);
const address = formData.get(FORM_FIELD_NAMES.ADDRESS);
if (!email || !password || !name || !address || !businessImg || !pharmImg) {
return alert("모든 항목을 입력해주세요");
}
if (error.email === true || error.password === true || error.name === true) {
return alert("항목을 다시 확인해주세요");
}
if (checks === false) {
return alert("회원가입시, 사용자의 현재 위치를 사용하는 것에 동의해주세요");
}
};