React에서 Parse 데이터 유형 활용하기: 개발자 가이드
9 분
리액트 컴포넌트에서 데이터 유형 파싱 소개 parse core 기능의 핵심은 데이터 객체 관리입니다 parse는 sdk 또는 api(rest 또는 graphql)를 사용하여 데이터를 간단하게 저장하고 쿼리할 수 있도록 합니다 모든 데이터 객체 기능은 \<font color="#2166ae">parse object\</font> 클래스를 사용하여 구축되며, 이 클래스의 필드는 여러 json 호환 데이터 유형의 키 값 쌍을 포함할 수 있습니다 객체 필드에 할당할 수 있는 주요 데이터 유형은 다음과 같습니다 \<font color="#2166ae">숫자\</font> 정수(42) 또는 부동 소수점(42 5) 숫자, ‘ ’가 소수 구분 기호인 경우; \<font color="#2166ae">부울\</font> true 또는 false 값; \<font color="#2166ae">문자열\</font> 최대 2147483647자까지의 문자열 이렇게 큰 값은 데이터 작업을 느리게 할 수 있습니다; \<font color="#2166ae">날짜 및 시간\</font> \<font color="#2166ae">날짜 및 시간\</font> 객체는 기본적으로 utc 형식으로 저장됩니다 다른 시간대를 사용해야 하는 경우 수동으로 변환해야 합니다; \<font color="#2166ae">배열\</font> parse와 호환되는 데이터가 포함된 배열 객체 parse 데이터를 포함하는 json 객체 sdk에서 사용할 수 있을 때, \<font color="#2166ae">include()\</font> 호출은 객체 속성의 세부 정보를 가져옵니다 array 유형을 사용하기로 선택할 때, 배열 객체를 작게 유지하는 것이 좋습니다 이는 데이터 작업의 전반적인 성능에 영향을 미칠 수 있습니다 20개 요소를 초과하지 않고 시간이 지남에 따라 증가하지 않는 경우 array 유형을 사용하는 것이 좋습니다 array 유형 대신 pointer 및 relations 유형을 대안으로 사용할 수 있습니다 이 가이드에서는 위에 나열된 각 기본 데이터 유형에 데이터를 저장하는 방법을 배웁니다 react에서 제품 등록 구성 요소를 구축하여 데이터를 형식화, 변환 및 parse server에 저장하는 방법을 보여줍니다 parse는 또한 지리 위치 리소스의 힘을 사용하기 위해 \<font color="#2166ae">geopoint \</font> 와 \<font color="#2166ae">pointer \</font> 또는 \<font color="#2166ae">relation\</font> 과 같은 parse 전용 관계형 데이터를 제공합니다 다음 가이드에서 두 가지 모두 다룰 것입니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 react 앱이 생성되고 back4app에 연결됨 https //www back4app com/docs/react/quickstart 이 가이드에서 제공하는 화면 레이아웃을 테스트/사용하려면 라이브러리를 설정해야 합니다 https //ant design/docs/react/introduce 목표 parse와 호환되는 기본 데이터 유형을 이해하고, react 구성 요소에서 각 데이터 유형을 parse에 저장하는 것입니다 1 제품 생성 구성 요소 먼저 구성 요소 구조를 만들어 보겠습니다 간단하게 만들고 각 데이터 유형에 대해 하나의 텍스트 입력, 하나의 체크박스 및 객체를 저장하기 위한 제출 버튼이 있는 양식 화면을 만듭니다 이러한 입력은 귀하의 \<font color="#2166ae">제품 \</font> 필드 값을 수집합니다 이름 ( \<font color="#2166ae">문자열\</font> ), 수량 ( \<font color="#2166ae">숫자\</font> ), 가격 ( \<font color="#2166ae">숫자\</font> ), 사용 가능 ( \<font color="#2166ae">부울\</font> ), 만료 날짜 ( \<font color="#2166ae">날짜 및 시간\</font> ), 및 카테고리( \<font color="#2166ae">배열\</font> ) 또한 저장 방법에서 추가 \<font color="#2166ae">객체 \</font> 유형 필드를 저장하지만, 이 필드는 입력 필드가 필요하지 않습니다 다음 코드를 포함하여 \<font color="#2166ae">productcreation js/productcreation tsx\</font> 라는 파일에 별도의 구성 요소를 만들거나, 주 애플리케이션 파일에 추가하십시오 ( \<font color="#2166ae">app js/app tsx\</font> ) 이 레이아웃은 \<font color="#2166ae">ant design\</font> 을 사용하여 완전한 스타일링으로 사용할 수 있으며, \<font color="#2166ae">app css\</font> 파일에 css 코드를 추가하거나 자신만의 사용자 정의 양식을 설정할 수 있습니다 productcreation js 1 import react, { usestate } from 'react'; 2 import parse from 'parse/dist/parse min js'; 3 import ' /app css'; 4 import { button, checkbox, input } from 'antd'; 5 import { plusoutlined } from '@ant design/icons'; 6 7 export const productcreation = () => { 8 // state variables 9 const \[productname, setproductname] = usestate(''); 10 const \[productquantity, setproductquantity] = usestate(''); 11 const \[productprice, setproductprice] = usestate(''); 12 const \[productavailable, setproductavailable] = usestate(false); 13 const \[productexpirationdate, setproductexpirationdate] = usestate(''); 14 const \[productcategories, setproductcategories] = usestate(''); 15 16 return ( 17 \<div> 18 \<div classname="header"> 19 \<img 20 classname="header logo" 21 alt="back4app logo" 22 src={ 23 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 24 } 25 /> 26 \<p classname="header text bold">{'react on back4app'}\</p> 27 \<p classname="header text">{'product creation'}\</p> 28 \</div> 29 \<div classname="container"> 30 {/ product field inputs /} 31 \<div classname="flex between"> 32 \<h2 classname="list heading">available?\</h2> 33 \<checkbox 34 onchange={(e) => setproductavailable(e target checked)} 35 >\</checkbox> 36 \</div> 37 \<div classname="form wrapper"> 38 \<input 39 classname="form input" 40 value={productname} 41 onchange={(event) => setproductname(event target value)} 42 placeholder="name" 43 size="large" 44 /> 45 \<input 46 classname="form input" 47 value={productquantity} 48 onchange={(event) => setproductquantity(event target value)} 49 placeholder="quantity" 50 size="large" 51 /> 52 \<input 53 classname="form input" 54 value={productprice} 55 onchange={(event) => setproductprice(event target value)} 56 placeholder="price" 57 size="large" 58 /> 59 \<input 60 classname="form input" 61 value={productexpirationdate} 62 onchange={(event) => setproductexpirationdate(event target value)} 63 placeholder="expiration date (mm/dd/yyyy)" 64 size="large" 65 /> 66 \<input 67 classname="form input" 68 value={productcategories} 69 onchange={(event) => setproductcategories(event target value)} 70 placeholder="categories (separated by comma)" 71 size="large" 72 /> 73 {/ add product button /} 74 \<button 75 type="primary" 76 classname="form button" 77 color={'#208aec'} 78 size={'large'} 79 onclick={createproduct} 80 icon={\<plusoutlined />} 81 > 82 create product 83 \</button> 84 \</div> 85 \</div> 86 \</div> 87 ); 88 }; productcreation tsx 1 import react, { usestate, fc, reactelement } from 'react'; 2 import ' /app css'; 3 import { button, checkbox, input } from 'antd'; 4 import { plusoutlined } from '@ant design/icons'; 5 const parse = require('parse/dist/parse min js'); 6 7 export const productcreation fc<{}> = () reactelement => { 8 // state variables 9 const \[productname, setproductname] = usestate(''); 10 const \[productquantity, setproductquantity] = usestate(''); 11 const \[productprice, setproductprice] = usestate(''); 12 const \[productavailable, setproductavailable] = usestate(false); 13 const \[productexpirationdate, setproductexpirationdate] = usestate(''); 14 const \[productcategories, setproductcategories] = usestate(''); 15 16 const createproduct = async function () promise\<boolean> { 17 try { 18 // these values come from state variables 19 // convert data values to corresponding data types 20 const productnamevalue string = productname; 21 const productquantityvalue number = number(productquantity); 22 const productpricevalue number = number(productprice); 23 const productavailablevalue boolean = productavailable; 24 const productexpirationdatevalue date = new date(productexpirationdate); 25 const productcategoriesvalue string\[] = productcategories split(','); 26 27 // creates a new product parse object instance 28 let product parse object = new parse object('product'); 29 30 // set data to parse object 31 product set('name', productnamevalue); 32 product set('quantity', productquantityvalue); 33 product set('price', productpricevalue); 34 product set('available', productavailablevalue); 35 product set('expirationdate', productexpirationdatevalue); 36 product set('categories', productcategoriesvalue); 37 product set('completedata', { 38 name productnamevalue, 39 quantity productquantityvalue, 40 price productpricevalue, 41 available productavailablevalue, 42 expirationdate productexpirationdatevalue, 43 categories productcategoriesvalue, 44 }); 45 46 // after setting the values, save it on the server 47 try { 48 let savedproduct parse object = await product save(); 49 // success 50 alert(`success! ${json stringify(savedproduct)}`); 51 return true; 52 } catch (error) { 53 // error can be caused by lack of internet connection 54 alert(`error! ${error message}`); 55 return false; 56 } 57 } catch (error any) { 58 // error can be caused by wrong type of values in fields 59 alert(`error! ${error message}`); 60 return false; 61 } 62 }; 63 64 return ( 65 \<div> 66 \<div classname="header"> 67 \<img 68 classname="header logo" 69 alt="back4app logo" 70 src={ 71 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 72 } 73 /> 74 \<p classname="header text bold">{'react on back4app'}\</p> 75 \<p classname="header text">{'product creation'}\</p> 76 \</div> 77 \<div classname="container"> 78 {/ product field inputs /} 79 \<div classname="flex between"> 80 \<h2 classname="list heading">available?\</h2> 81 \<checkbox 82 onchange={(e) => setproductavailable(e target checked)} 83 >\</checkbox> 84 \</div> 85 \<div classname="form wrapper"> 86 \<input 87 classname="form input" 88 value={productname} 89 onchange={(event) => setproductname(event target value)} 90 placeholder="name" 91 size="large" 92 /> 93 \<input 94 classname="form input" 95 value={productquantity} 96 onchange={(event) => setproductquantity(event target value)} 97 placeholder="quantity" 98 size="large" 99 /> 100 \<input 101 classname="form input" 102 value={productprice} 103 onchange={(event) => setproductprice(event target value)} 104 placeholder="price" 105 size="large" 106 /> 107 \<input 108 classname="form input" 109 value={productexpirationdate} 110 onchange={(event) => setproductexpirationdate(event target value)} 111 placeholder="expiration date (mm/dd/yyyy)" 112 size="large" 113 /> 114 \<input 115 classname="form input" 116 value={productcategories} 117 onchange={(event) => setproductcategories(event target value)} 118 placeholder="categories (separated by comma)" 119 size="large" 120 /> 121 {/ add product button /} 122 \<button 123 type="primary" 124 classname="form button" 125 color={'#208aec'} 126 size={'large'} 127 onclick={createproduct} 128 icon={\<plusoutlined />} 129 > 130 create product 131 \</button> 132 \</div> 133 \</div> 134 \</div> 135 ); 136 }; 1 html { 2 box sizing border box; 3 outline none; 4 overflow auto; 5 } 6 7 , 8 before, 9 after { 10 margin 0; 11 padding 0; 12 box sizing inherit; 13 } 14 15 h1, 16 h2, 17 h3, 18 h4, 19 h5, 20 h6 { 21 margin 0; 22 } 23 24 p { 25 margin 0; 26 } 27 28 body { 29 margin 0; 30 background color #fff; 31 } 32 33 container { 34 width 100%; 35 max width 600px; 36 margin auto; 37 padding 20px 0; 38 } 39 40 header { 41 align items center; 42 padding 25px 0; 43 background color #208aec; 44 } 45 46 header logo { 47 height 55px; 48 margin bottom 20px; 49 object fit contain; 50 } 51 52 header text bold { 53 margin bottom 3px; 54 color rgba(255, 255, 255, 0 9); 55 font size 16px; 56 font weight bold; 57 } 58 59 header text { 60 color rgba(255, 255, 255, 0 9); 61 font size 15px; 62 } 63 64 flex between { 65 display flex; 66 align items center; 67 justify content space between; 68 } 69 70 list heading { 71 font weight bold; 72 } 73 74 form wrapper { 75 margin top 20px; 76 margin bottom 10px; 77 } 78 79 form input { 80 margin bottom 20px; 81 } 82 83 form button { 84 width 100%; 85 } 이 화면을 설정한 후, 귀하의 애플리케이션은 다음과 같아야 합니다 각 \<font color="#2166ae">제품 \</font> 속성에는 불리언 체크박스 입력을 제외하고는 각기 텍스트 입력 필드가 있다는 점에 유의하십시오 이는 저장하기 전에 해당 데이터 유형으로 변환해야 함을 의미합니다 2 입력 데이터 변환 데이터를 \<font color="#2166ae">parse object\</font> , 저장하기 전에 \<font color="#2166ae">number\</font> , \<font color="#2166ae">datetime\</font> , 및 \<font color="#2166ae">array \</font> 입력을 올바르게 형식화해야 합니다 이제 상태 변수에서 데이터를 검색하고 적절한 데이터 변환을 적용하는 저장 함수를 만들어 보겠습니다 productcreation js 1 const createproduct = async function () { 2 try { 3 // these values come from state variables 4 // convert data values to corresponding data types 5 const productnamevalue = productname; 6 const productquantityvalue = number(productquantity); 7 const productpricevalue = number(productprice); 8 const productavailablevalue = productavailable; 9 const productexpirationdatevalue = new date(productexpirationdate); 10 const productcategoriesvalue = productcategories split(','); 11 } catch (error) { 12 // error can be caused by wrong type of values in fields 13 alert(`error! ${error message}`); 14 return false; 15 } 16 }; productcreation tsx 1 const createproduct = async function () promise\<boolean> { 2 try { 3 // these values come from state variables 4 // convert data values to corresponding data types 5 const productnamevalue string = productname; 6 const productquantityvalue number = number(productquantity); 7 const productpricevalue number = number(productprice); 8 const productavailablevalue boolean = productavailable; 9 const productexpirationdatevalue date = new date(productexpirationdate); 10 const productcategoriesvalue string\[] = productcategories split(','); 11 } catch (error any) { 12 // error can be caused by wrong type of values in fields 13 alert(`error! ${error message}`); 14 return false; 15 } 16 }; 숫자 \<font color="#2166ae">데이터 변환은 값을 \</font> 로 캐스팅하여 수행됩니다 \<font color="#2166ae">number\</font> 자바스크립트 객체로 \<font color="#2166ae">datetime \</font> 은 \<font color="#2166ae">date \</font> 자바스크립트 객체 생성자를 사용하여 변환됩니다 \<font color="#2166ae">배열 \</font> 하나는 \<font color="#2166ae">string split\</font> 메서드를 사용하여 생성되며, 카테고리 필드의 각 항목이 쉼표로 구분된 배열을 생성합니다 당신의 데이터는 이제 단일 객체 안에 포함되어 있으며, 이는 새로운 p \<font color="#2166ae">arse object \</font> 인스턴스에 설정되어 \<font color="#2166ae">parse object set()\</font> 메서드를 사용하여 서버에 저장될 수 있습니다 이 메서드는 두 개의 인수를 받습니다 필드 이름과 설정할 값입니다 또한 \<font color="#2166ae">completedata\</font> 라는 새로운 필드를 설정해 보겠습니다 이는 당신의 \<font color="#2166ae">객체 \</font> 유형 필드가 되며, 동일한 데이터 객체를 할당합니다 계속해서 다음과 함께 \<font color="#2166ae">createproduct \</font> 함수를 완성하세요 productcreation js 1 const createproduct = async function () { 2 try { 3 // these values come from state variables 4 // convert data values to corresponding data types 5 const productnamevalue = productname; 6 const productquantityvalue = number(productquantity); 7 const productpricevalue = number(productprice); 8 const productavailablevalue = productavailable; 9 const productexpirationdatevalue = new date(productexpirationdate); 10 const productcategoriesvalue = productcategories split(','); 11 12 // creates a new product parse object instance 13 let product = new parse object('product'); 14 15 // set data to parse object 16 product set('name', productnamevalue); 17 product set('quantity', productquantityvalue); 18 product set('price', productpricevalue); 19 product set('available', productavailablevalue); 20 product set('expirationdate', productexpirationdatevalue); 21 product set('categories', productcategoriesvalue); 22 product set('completedata', { 23 name productnamevalue, 24 quantity productquantityvalue, 25 price productpricevalue, 26 available productavailablevalue, 27 expirationdate productexpirationdatevalue, 28 categories productcategoriesvalue, 29 }); 30 31 // after setting the values, save it on the server 32 try { 33 let savedproduct = await product save(); 34 // success 35 alert(`success! ${json stringify(savedproduct)}`); 36 return true; 37 } catch (error) { 38 // error can be caused by lack of internet connection 39 alert(`error! ${error message}`); 40 return false; 41 } 42 } catch (error) { 43 // error can be caused by wrong type of values in fields 44 alert(`error! ${error message}`); 45 return false; 46 } 47 }; productcreation tsx 1 const createproduct = async function () promise\<boolean> { 2 try { 3 // these values come from state variables 4 // convert data values to corresponding data types 5 const productnamevalue string = productname; 6 const productquantityvalue number = number(productquantity); 7 const productpricevalue number = number(productprice); 8 const productavailablevalue boolean = productavailable; 9 const productexpirationdatevalue date = new date(productexpirationdate); 10 const productcategoriesvalue string\[] = productcategories split(','); 11 12 // creates a new product parse object instance 13 let product parse object = new parse object('product'); 14 15 // set data to parse object 16 product set('name', productnamevalue); 17 product set('quantity', productquantityvalue); 18 product set('price', productpricevalue); 19 product set('available', productavailablevalue); 20 product set('expirationdate', productexpirationdatevalue); 21 product set('categories', productcategoriesvalue); 22 product set('completedata', { 23 name productnamevalue, 24 quantity productquantityvalue, 25 price productpricevalue, 26 available productavailablevalue, 27 expirationdate productexpirationdatevalue, 28 categories productcategoriesvalue, 29 }); 30 31 // after setting the values, save it on the server 32 try { 33 let savedproduct parse object = await product save(); 34 // success 35 alert(`success! ${json stringify(savedproduct)}`); 36 return true; 37 } catch (error any) { 38 // error can be caused by lack of internet connection 39 alert(`error! ${error message}`); 40 return false; 41 }; 42 } catch (error any) { 43 // error can be caused by wrong type of values in fields 44 alert(`error! ${error message}`); 45 return false; 46 } 47 }; 이제 구성 요소를 테스트할 수 있으며, \<font color="#2166ae">createproduct \</font> 함수를 삽입하고, 양식 제출 버튼의 \<font color="#2166ae">onclick \</font> 속성 내에서 호출해야 합니다 제품을 생성한 후에는 다음과 같은 데이터가 포함된 경고가 표시되어야 합니다 서버에 올바른 데이터 유형을 사용하여 데이터가 저장되었음을 인증하려면 parse 대시보드를 확인할 수 있습니다 \<font color="#2166ae">제품 \</font> 데이터 테이블을 클릭하고 각 열의 헤더에 데이터 유형이 적혀 있는지 확인하세요 당신의 클래스는 다음과 같아야 합니다 결론 이 가이드의 끝에서, react 컴포넌트를 사용하여 parse에서 사용할 수 있는 기본 데이터 유형을 저장하는 방법을 배웠습니다 다음 가이드에서는 parse의 관계형 데이터에 대해 배울 것입니다