[React.js] 비슷한 구조의 state 다루기

2024. 6. 10. 09:19React.js

728x90

https://mm-study-front.tistory.com/40

 

 

이 코드를 자세히 보면

  const [namesetName= useState("이름");
  const [birthsetBirth= useState("YYYY-MM-DD");
  const [countrysetCountry= useState("국적");
  const [gendersetGender= useState("성별")
  const [resonsetReson= useState("이유");
 
  const onChangeName = (e=> {setName(e.target.value)};
  const onChangeBirth = (e=> {setBirth(e.target.value)};
  const onChangeCountry = (e=> {setCountry(e.target.value)};
  const onChangeGender = (e=> {setGender(e.target.value)};
  const onChangereson = (e=> { setReson(e.target.value)};
 
변수와 이벤트 핸들러가 거의 똑같은 구조로 반복된다.
즉 중복된 코드가 너무 많다 
앞으로도 리액트 컴포넌트에 여러개의 state가 많을텐데
그럼 그때마다 많은 중복된 코드를 써야할까
 
 
→근데 이건 진짜 너무 비효율적
그러면 어떻게?
 
비슷한 구조의 state들은 객체로 다루기
비슷한 이벤트 핸들러는 하나의 공통된 핸들러로 만들기
 

물론 정말 비효율적으로 중복될 때만 함부로 합치면 오류나 관리가 어려워진다


const Information = () => {
  const [infor, setInfor] = useState({
    name: "이름",
    birth: "YYYY-MM-DD",
    country: "국적",
    gender: "성별",
    reson: "이유",
  });

 

state는 객체로 하나로 다루고

 

  const onChange = (e) => {
    setInfor({
      ...infor,
      [e.target.name]: e.target.value,
    });
  };

 

이벤트핸들러도 하나로 합쳐서 공통된 함수로 사용

이때

 ...infor  를 사용하지 않으면

나는 이름을 치고 생년월일을 추가로 설정했는데 이름 값이 저렇게 바뀐거다,,

 

state 넣을 때마다 각각의 값에 제대로 입력되지 않는다

 

태그들도

  return (
    <div>
      <div>
        <p>이름</p>
        <input
          name="name"
          value={infor.name}
          onChange={onChange}
          placeholder={"이름"}
        />
        {infor.name}
      </div>
      <div>
        <p>생년월일</p>
        <input
          name="name"
          value={infor.birth}
          onChange={onChange}
          type="date"
        />
        {infor.birth}
      </div>
      <div>
        <p>국적</p>
        <select name="country" value={infor.country} onChange={onChange}>
          <option value=""></option>
          <option value="kr">한국</option>
          <option value="us">미국</option>
          <option value="uk">영국</option>
          <option value="jp">일본</option>
        </select>
        {infor.country}
      </div>
      <div>
        <p>성별</p>
        <input type="radio" onChange={onChange} name="gender" value="m" />
        남성
        <input type="radio" onChange={onChange} name="gender" value="f" />
        여성
        {infor.gender}
      </div>
      <div>
        <p>가입이유</p>
        <textarea
          name="reason"
          value={infor.reson}
          placeholder="가입하게된 이유를 적어주세요"
          onChange={onChange}
        ></textarea>
      </div>
    </div>
  );

 

이렇게 바꿔주기

 

728x90

'React.js' 카테고리의 다른 글

[React.js] React Hooks  (0) 2024.06.12
[React.js]useRef  (0) 2024.06.11
[React.js] 실습1. 간단한 정보기입 폼  (0) 2024.06.09
[React.js] State와 Props  (0) 2024.06.08
[React.js] State  (0) 2024.06.07