You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
데이터를 더 잘 관리하고 애플리케이션 디버깅에 걸리는 시간을 줄이는 기법에 대해서 살펴본다.
리액트 컴포넌트 안에서 데이터를 처리하는 방법에 대해서 살펴본다.
6.1 프로퍼티 검증
자바스크립트는 타입 검증에 느슨한 언어
변수 타입을 비효율적으로 다루면 애플리케이션을 디버깅할 때 오래 걸릴 수 있다.
리액트에서는 타입을 지정하고 검증하는 방법을 제공
prop-types 패키지를 설치 후 사용 가능
importPropTypesfrom'prop-types';MyComponent.propTypes={// 자바스크립트 기본 타입은 기본적으로 다 지원한다.optionalArray: PropTypes.array,optionalBool: PropTypes.bool,optionalFunc: PropTypes.func,optionalNumber: PropTypes.number,optionalObject: PropTypes.object,optionalString: PropTypes.string,optionalSymbol: PropTypes.symbol,// 랜더링 할 수 있는 모든 것(숫자, 문자, element, 배열)을 다 지원하는 타입optionalNode: PropTypes.node,// 리액트 elementoptionalElement: PropTypes.element,// 특정 클래스의 인스턴스인지 여부를 체크 optionalMessage: PropTypes.instanceOf(Message),// 특정한 값만 가능하도록 체크optionalEnum: PropTypes.oneOf(['News','Photos']),// 특정 타입만 가능하도록 체크optionalUnion: PropTypes.oneOfType([PropTypes.string,PropTypes.number,PropTypes.instanceOf(Message)]),// 특정 타입의 배열만 가능하도록 체크optionalArrayOf: PropTypes.arrayOf(PropTypes.number),// 특정 타입의 값만 가지고 있는 object 인지 체크optionalObjectOf: PropTypes.objectOf(PropTypes.number),// 해당 형태의 object인지 체크optionalObjectWithShape: PropTypes.shape({color: PropTypes.string,fontSize: PropTypes.number}),// 필수 값 체크requiredFunc: PropTypes.func.isRequired,// 필수 값만 체크. 어떤 값도 와도 됨requiredAny: PropTypes.any.isRequired,// 커스텀 검증customProp: function(props,propName,componentName){if(!/matchme/.test(props[propName])){returnnewError('Invalid prop `'+propName+'` supplied to'+' `'+componentName+'`. Validation failed.');}},// You can also supply a custom validator to `arrayOf` and `objectOf`.// It should return an Error object if the validation fails. The validator// will be called for each key in the array or object. The first two// arguments of the validator are the array or object itself, and the// current item's key.customArrayProp: PropTypes.arrayOf(function(propValue,key,componentName,location,propFullName){if(!/matchme/.test(propValue[key])){returnnewError('Invalid prop `'+propFullName+'` supplied to'+' `'+componentName+'`. Validation failed.');}})};
6.1.1. createClass로 프로퍼티 검증하기
Summary 클래스를 만든다.
import{Component}from'react';constSummary=classextendsComponent{constructor(props){super(props);}render(){const{ ingredients, steps, title }=this.props;return(<divclassName="summary"><h1>{title}</h1><p><span>재료 {ingredients.length} 종류 | </span><span>총 {steps.length}</span></p></div>);}}returnSummary;
프로퍼티 검증이 들어가 있지 않기 때문에 아래와 같은 경우 우리가 예상되는 결과 값을 생성하지 않는다.
// ingredients, steps 가 문자열이기 때문에 문자열의 길이 값이 결과로 나온다.// 이 부분은 우리가 예상하지 못한 결과이고 이런 건 디버깅 하기가 너무 힘들다.render(<Summarytitle="땅콩버터와 젤리"ingredients="땅콩버터, 젤리, 식빵"steps="땅콩버터와 젤리를 넓게 바른 식빵 두 장을 바른 명이 안으로 가도록 겹친다."/>,document.getElementById("react-container"));// ingredients, steps 가 없는 경우 에러가 나온다.// ingredients, steps 의 경우 배열 값이라는 가장 하에 length 값을 주었지만 식제 값은 null 값이기 때문에 null에는 length 속성 값이 없어서 에러가 발생render(<Summary/>,document.getElementById("react-container"));
타입 검증을 추가하면 아래와 같다.
importReact,{Component}from'react';importPropTypesfrom'prop-types';constSummary=classextendsComponent{render(){const{ ingredients, steps, title }=this.props;return(<divclassName="summary"><h1>{title}</h1><p><span>재료 {ingredients.length} 종류 | </span><span>총 {steps.length}</span></p></div>);}staticpropTypes={ingredients: PropTypes.array.isRequired,steps: PropTypes.array.isRequired,title: PropTypes.string}}exportdefaultSummary;
위와 같이 처리할 경우에 ingredients와 steps가 배열이 아니기 때문에 콘솔 창에 경고가 표시된다.
경고는 표시되지만 실제 프로그램은 실행된다.
6.1.2 디폴트 프로퍼티
값을 무조건 지정할 수 있도록 위와 같이 isRequired 를 설정하는 것도 좋은 방법이지만 디폴트 값을 지정하는 방법도 존재한다.
importReact,{Component}from'react';importPropTypesfrom'prop-types';constSummary=classextendsComponent{render(){const{ ingredients, steps, title }=this.props;return(<divclassName="summary"><h1>{title}</h1><p><span>재료 {ingredients.length} 종류 | </span><span>총 {steps.length}</span></p></div>);}staticpropTypes={ingredients: PropTypes.array,steps: PropTypes.array,title: PropTypes.string}// 이런 식으로 디폴트 설정이 가능staticdefaultProps={ingredients: [],steps: [],title: ''}}exportdefaultSummary;
6.1.3. 커스텀 프로퍼티 검증
필수 값이나 타입 검증만으로 검증이 되지 않을 때 커스텀 프로퍼티 검증을 사용
특정 값의 범위를 지정한다던가, 문자열 안에 꼭 들어가야 하는 부분 문자열 검사 등등
함수로 구현
요구 사항을 만족하지 않는 경우 error를 반환, 요구 사항을 만족하면 null 을 반환