티스토리 뷰

웹개발(프론트)/React

자료형 검사하기

수달찌 2021. 4. 24. 21:35

 

 

제목을 쓸 때 해당 함수(패키지) 명을 써야 사람들이 들어오기 편할까,

해당 오브젝트가 하는 일을 적어야 들어오기 편할까?

 

으음... 내가 뭔가 모르는데 이러한 툴을 쓰고 싶어서 검색한다면

함수나 패키지 명보다는 하는 일을 적는게 더 편할 것 같긴 한데

 

갑자기 제목을 어떻게 써야 할지 고민됐다.

익숙했던 것을 돌아볼 수 있다는 건 좋은 일인 것 같다.

PropTypes

금액 데이터를 받았는데 숫자가 아닌 문자로 다른 자료형으로 되어있다.

그래서 계산식에서 에러가 떴는데 어디서 문제가 생겼는지 알려주는 것,

그것이 PropTypes의 용도이다.

코드

//App.js
import React from "react";
import PropTypes from 'prop-types';

function UserInfo({name, age, email, citizen}){
  return(
    <>
      <h2>이름 : {name}</h2>
      <h2>나이 : {age}</h2>
      <h2>메일주소 : {email}</h2>
      <h2>내국인 : {citizen ? ("true"):("false")}</h2>
    </>
  )
}

UserInfo.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  email: PropTypes.string.isRequired,
  citizen: PropTypes.bool,
}

function App() {

  return (
    <UserInfo
      name = {"Tom"}
      age = {"twenty eight"}
      email = {"abc@google.com"}
      citizen = {false}
      />
  );
}

export default App;

 

해석

//App.js

function App() {

  return (
    <UserInfo
      name = {"Tom"}
      age = {"twenty eight"}
      email = {"abc@google.com"}
      citizen = {false}
      />
  );
}

export default App;

App 컴포넌트는

UserInfo 컴포넌트에

name age email citizen 4개의 데이터를 전해주고 있다.

//App.js
import React from "react";
import PropTypes from 'prop-types';

UserInfo.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  email: PropTypes.string.isRequired,
  citizen: PropTypes.bool,
}

export default App;

이때

propTypes를 써서

UserInfo의 인자(prop) 자료형(types)를 지정해준다.

  • name 문자
  • age 숫자
  • email 문자(필요)
  • citizen 참/거짓(bool)
//App.js

function App() {

  return (
    <UserInfo
      name = {"Tom"}
      age = {"twenty eight"}
      email = {"abc@google.com"}
      citizen = {false}
      />
  );
}

export default App;

그런데 App에서 넘겨주는 데이터중에서

age를 문자로 넘겨주었다.

그렇기에 console창에서 경고가 출력되었다.

라이브러리

예제 코드에선 자주 쓰이는 것만 간단하게 적었지만,

React 공식 홈페이지를 찾으면

해당 패키지의 모든 라이브러리를 알아볼 수 있다.

 

PropTypes와 함께 하는 타입 확인 – React

A JavaScript library for building user interfaces

ko.reactjs.org

매개변수 기본값 설정

 

defaultProps를 쓰면 매개변수 기본값을 설정해 줄 수 있다.

 

 

매개변수 초기화

목차 흐음... 일단 매개변수 초기화를 함으로써 어떤 장점이 있는지는 아직 잘 모르겠지만 알아둬서 나쁠 건 없다고 생각한다. 생각해보니 그렇다면 이건 도토리에 들어갈 내용이구만 Initialize fu

sirong.tistory.com

지난 포스트에 바로 해당 오브젝트에 적는 법도 있지만,

여러 스타일의 개발자가 있으니 이런 것도 있구나 하고 알아두는 게 좋다.

//App.js
import React from "react";
import PropTypes from 'prop-types';

function App() {

  return (
    <UserInfo/>
  );
}

function UserInfo({name, age, email, citizen}){
  return(
    <>
      <h2>이름 : {name}</h2>
      <h2>나이 : {age}</h2>
      <h2>메일주소 : {email}</h2>
      <h2>내국인 : {citizen ? ("true"):("false")}</h2>
    </>
  )
}

UserInfo.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  email: PropTypes.string.isRequired,
  citizen: PropTypes.bool,
}

UserInfo.defaultProps = {
  name : 'Tom',
  age : "twenty eight",
  email : "abc@google.com",
  citizen : false,
}

export default App;

defaultProps.를 통해 기본값을 지정해주었다.

에러 중첩 X

propTypes 경고가 여러개 있을 때 두 개 모두 알려주는 게 아니라,

앞에 것만 알려준다.

//App.js
import React from "react";
import PropTypes from 'prop-types';

function App() {

  return (
    <UserInfo/>
  );
}

function UserInfo({name, age, email, citizen}){
  return(
    <>
      <h2>이름 : {name}</h2>
      <h2>나이 : {age}</h2>
      <h2>메일주소 : {email}</h2>
      <h2>내국인 : {citizen ? ("true"):("false")}</h2>
    </>
  )
}

UserInfo.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  email: PropTypes.string.isRequired,
  citizen: PropTypes.bool,
}

UserInfo.defaultProps = {
  name : 'Tom',
  age : "twenty eight",
  citizen : false,
}

export default App;

해당 코드에선

age에 문자를 넣고 / email 데이터를 안 넣어주었으니

2개의 warning이 떠야 하는데

앞에 것 하나만 뜬다.

//App.js
import React from "react";
import PropTypes from 'prop-types';

function App() {

  return (
    <UserInfo/>
  );
}

function UserInfo({name, age, email, citizen}){
  return(
    <>
      <h2>이름 : {name}</h2>
      <h2>나이 : {age}</h2>
      <h2>메일주소 : {email}</h2>
      <h2>내국인 : {citizen ? ("true"):("false")}</h2>
    </>
  )
}

UserInfo.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  email: PropTypes.string.isRequired,
  citizen: PropTypes.bool,
}

UserInfo.defaultProps = {
  name : 'Tom',
  age : 28,
  citizen : false,
}

export default App;

앞에 warning 요소를 해결해주면

뒤에 warning요소가 뜬다.

 

큰 건 아니지만

warning 하나 떠서 하나만 고치고 바로 제출하거나 그러면 일이 커지니깐

한번 보고 지나가는 것도 좋다고 생각한다.

'웹개발(프론트) > React' 카테고리의 다른 글

And 연산자  (1) 2021.05.12
Redux-slice  (0) 2021.04.25
React cookie  (0) 2021.04.20
createElement 스타일 변경  (0) 2021.04.18
styled components 심화편  (0) 2021.04.17
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함