React Native
...
Data objects
Data types
9 분
리액트 네이티브 컴포넌트에서 데이터 유형 파싱 소개 parse core 기능의 핵심은 데이터 객체 관리입니다 parse는 sdk 또는 api(rest 또는 graphql)를 사용하여 데이터를 간단하게 저장하고 쿼리할 수 있도록 합니다 모든 데이터 객체 기능은 parse object parse object 클래스를 사용하여 구축되며, 이 클래스의 필드는 여러 json 호환 데이터 유형의 키 값 쌍을 포함할 수 있습니다 객체 필드에 할당할 수 있는 주요 데이터 유형은 다음과 같습니다 숫자 숫자 정수(42) 또는 부동 소수점(42 5) 숫자, ‘ ’가 소수 구분 기호인 경우; 부울 부울 true 또는 false 값; 문자열 문자열 최대 2147483647자까지의 문자열 이렇게 큰 값은 데이터 작업을 느리게 할 수 있습니다; 날짜 및 시간 날짜 및 시간 날짜 및 시간 날짜 및 시간 객체는 기본적으로 utc 형식으로 저장됩니다 다른 시간대를 사용해야 하는 경우 수동으로 변환해야 합니다; 배열 배열 parse와 호환되는 데이터가 포함된 배열 객체 객체 json 객체로, parse 데이터도 포함됩니다 sdk에서 사용할 수 있을 때, include() include() 호출은 객체 속성의 세부 정보를 가져옵니다 array 유형을 사용하기로 선택할 때, 배열 객체를 작게 유지하는 것이 좋습니다 이는 데이터 작업의 전반적인 성능에 영향을 미칠 수 있습니다 20개 요소를 초과하지 않고 시간이 지남에 따라 증가하지 않는 경우 array 유형을 사용하는 것이 좋습니다 array 유형 대신 pointer 및 relation 유형을 대안으로 사용할 수 있습니다 이 가이드에서는 위에 나열된 각 기본 데이터 유형에 데이터를 저장하는 방법을 배웁니다 react native 제품 등록 구성 요소를 구축하여 데이터를 형식화, 변환 및 parse server에 저장하는 방법을 보여줍니다 parse는 또한 지리적 위치 리소스의 힘을 사용하기 위해 geopoint geopoint 와 pointer pointer 또는 relation relation 을 사용하여 parse 전용 관계형 데이터를 제공합니다 다음 가이드에서 두 가지 모두 다룰 것입니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 back4app에 연결된 react native 앱 이 가이드에서 제공하는 화면 레이아웃을 테스트/사용하려면 react native paper react native paper 를 설정해야 합니다 라이브러리 목표 parse와 호환되는 기본 데이터 유형을 이해하고, react native 구성 요소에서 각 데이터 유형을 parse에 저장하는 것입니다 1 제품 생성 구성 요소 먼저 구성 요소 구조를 생성해 보겠습니다 간단하게 만들고 각 데이터 유형에 대해 하나의 텍스트 입력, 하나의 스위치 토글, 그리고 객체를 저장하기 위한 제출 버튼이 있는 양식 화면을 만듭니다 이러한 입력은 다음과 같은 제품 제품 필드 값을 수집합니다 이름( 문자열 문자열 ), 수량( 숫자 숫자 ), 가격( 숫자 숫자 ), 사용 가능( 부울 부울 ), 만료 날짜( 날짜 및 시간 날짜 및 시간 ), 및 카테고리( 배열 배열 ) 또한, 저장 방법에서 추가 객체 객체 유형 필드를 저장할 것이지만, 이 필드는 입력 필드가 필요하지 않습니다 다음 코드를 포함하여 productcreation js/productcreation tsx productcreation js/productcreation tsx 라는 파일에 별도의 컴포넌트를 생성하거나, 주요 애플리케이션 파일( app js/app tsx app js/app tsx 또는 index js index js )에 추가하세요 react native paper react native paper 를 사용하여 완전한 스타일링으로 이 레이아웃을 사용할 수 있거나, 사용자 정의 양식을 설정할 수 있습니다 productcreation js 1 import react, {usestate} from 'react'; 2 import { 3 alert, 4 image, 5 safeareaview, 6 statusbar, 7 stylesheet, 8 view, 9 } from 'react native'; 10 import parse from 'parse/react native'; 11 import { 12 button as paperbutton, 13 switch as paperswitch, 14 text as papertext, 15 textinput as papertextinput, 16 } from 'react native paper'; 17	 18 export const productcreation = () => { 19 // state variables 20 const \[productname, setproductname] = usestate(''); 21 const \[productquantity, setproductquantity] = usestate(''); 22 const \[productprice, setproductprice] = usestate(''); 23 const \[productavailable, setproductavailable] = usestate(false); 24 const \[productexpirationdate, setproductexpirationdate] = usestate(''); 25 const \[productcategories, setproductcategories] = usestate(''); 26	 27 const toggleproductavailable = () => setproductavailable(!productavailable); 28	 29 return ( 30 <> 31 \<statusbar backgroundcolor="#208aec" /> 32 \<safeareaview style={styles container}> 33 \<view style={styles header}> 34 \<image 35 style={styles header logo} 36 source={ { uri 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', } } 37 /> 38 \<papertext style={styles header text bold}> 39 {'react native on back4app'} 40 \</papertext> 41 \<papertext style={styles header text}>{'product creation'}\</papertext> 42 \</view> 43 \<view style={styles wrapper}> 44 {/ boolean type input /} 45 \<view style={styles switch container}> 46 \<papertext>{'available?'}\</papertext> 47 \<paperswitch 48 value={productavailable} 49 onvaluechange={toggleproductavailable} 50 /> 51 \</view> 52 {/ string type input /} 53 \<papertextinput 54 value={productname} 55 onchangetext={(text) => setproductname(text)} 56 label="name" 57 mode="outlined" 58 style={styles form input} 59 /> 60 {/ number type input (integer) /} 61 \<papertextinput 62 value={productquantity} 63 onchangetext={(text) => setproductquantity(text)} 64 label="quantity" 65 mode="outlined" 66 keyboardtype={'number pad'} 67 style={styles form input} 68 /> 69 {/ number type input (float) /} 70 \<papertextinput 71 value={productprice} 72 onchangetext={(text) => setproductprice(text)} 73 label="price" 74 mode="outlined" 75 keyboardtype={'numeric'} 76 style={styles form input} 77 /> 78 {/ date type input /} 79 \<papertextinput 80 value={productexpirationdate} 81 onchangetext={(text) => setproductexpirationdate(text)} 82 label="expiration date (mm/dd/yyyy)" 83 mode="outlined" 84 keyboardtype={'numbers and punctuation'} 85 style={styles form input} 86 /> 87 {/ array type input /} 88 \<papertextinput 89 value={productcategories} 90 onchangetext={(text) => setproductcategories(text)} 91 label="categories (separated by commas)" 92 mode="outlined" 93 style={styles form input} 94 /> 95 {/ product create button /} 96 \<paperbutton 97 onpress={() => createproduct()} 98 mode="contained" 99 icon="plus" 100 style={styles submit button}> 101 {'create product'} 102 \</paperbutton> 103 \</view> 104 \</safeareaview> 105 \</> 106 ); 107 }; 108	 109 // these define the screen component styles 110 const styles = stylesheet create({ 111 container { 112 flex 1, 113 backgroundcolor '#fff', 114 }, 115 wrapper { 116 width '90%', 117 alignself 'center', 118 }, 119 header { 120 alignitems 'center', 121 paddingtop 10, 122 paddingbottom 20, 123 backgroundcolor '#208aec', 124 }, 125 header logo { 126 width 170, 127 height 40, 128 marginbottom 10, 129 resizemode 'contain', 130 }, 131 header text bold { 132 color '#fff', 133 fontsize 14, 134 fontweight 'bold', 135 }, 136 header text { 137 margintop 3, 138 color '#fff', 139 fontsize 14, 140 }, 141 form input { 142 height 44, 143 marginbottom 16, 144 backgroundcolor '#fff', 145 fontsize 14, 146 }, 147 switch container { 148 flexdirection 'row', 149 alignitems 'center', 150 justifycontent 'space between', 151 paddingvertical 12, 152 marginbottom 16, 153 borderbottomwidth 1, 154 borderbottomcolor 'rgba(0, 0, 0, 0 3)', 155 }, 156 submit button { 157 width '100%', 158 maxheight 50, 159 alignself 'center', 160 backgroundcolor '#208aec', 161 }, 162 }); productcreation tsx 1 import react, {fc, reactelement, usestate} from 'react'; 2 import { 3 alert, 4 image, 5 safeareaview, 6 statusbar, 7 stylesheet, 8 view, 9 } from 'react native'; 10 import parse from 'parse/react native'; 11 import { 12 button as paperbutton, 13 switch as paperswitch, 14 text as papertext, 15 textinput as papertextinput, 16 } from 'react native paper'; 17	 18 export const productcreation fc<{}> = ({}) reactelement => { 19 // state variables 20 const \[productname, setproductname] = usestate(''); 21 const \[productquantity, setproductquantity] = usestate(''); 22 const \[productprice, setproductprice] = usestate(''); 23 const \[productavailable, setproductavailable] = usestate(false); 24 const \[productexpirationdate, setproductexpirationdate] = usestate(''); 25 const \[productcategories, setproductcategories] = usestate(''); 26	 27 const toggleproductavailable = () => setproductavailable(!productavailable); 28	 29 return ( 30 <> 31 \<statusbar backgroundcolor="#208aec" /> 32 \<safeareaview style={styles container}> 33 \<view style={styles header}> 34 \<image 35 style={styles header logo} 36 source={ { uri 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', } } 37 /> 38 \<papertext style={styles header text bold}> 39 {'react native on back4app'} 40 \</papertext> 41 \<papertext style={styles header text}>{'product creation'}\</papertext> 42 \</view> 43 \<view style={styles wrapper}> 44 {/ boolean type input /} 45 \<view style={styles switch container}> 46 \<papertext>{'available?'}\</papertext> 47 \<paperswitch 48 value={productavailable} 49 onvaluechange={toggleproductavailable} 50 /> 51 \</view> 52 {/ string type input /} 53 \<papertextinput 54 value={productname} 55 onchangetext={(text) => setproductname(text)} 56 label="name" 57 mode="outlined" 58 style={styles form input} 59 /> 60 {/ number type input (integer) /} 61 \<papertextinput 62 value={productquantity} 63 onchangetext={(text) => setproductquantity(text)} 64 label="quantity" 65 mode="outlined" 66 keyboardtype={'number pad'} 67 style={styles form input} 68 /> 69 {/ number type input (float) /} 70 \<papertextinput 71 value={productprice} 72 onchangetext={(text) => setproductprice(text)} 73 label="price" 74 mode="outlined" 75 keyboardtype={'numeric'} 76 style={styles form input} 77 /> 78 {/ date type input /} 79 \<papertextinput 80 value={productexpirationdate} 81 onchangetext={(text) => setproductexpirationdate(text)} 82 label="expiration date (mm/dd/yyyy)" 83 mode="outlined" 84 keyboardtype={'numbers and punctuation'} 85 style={styles form input} 86 /> 87 {/ array type input /} 88 \<papertextinput 89 value={productcategories} 90 onchangetext={(text) => setproductcategories(text)} 91 label="categories (separated by commas)" 92 mode="outlined" 93 style={styles form input} 94 /> 95 {/ product create button /} 96 \<paperbutton 97 onpress={() => createproduct()} 98 mode="contained" 99 icon="plus" 100 style={styles submit button}> 101 {'create product'} 102 \</paperbutton> 103 \</view> 104 \</safeareaview> 105 \</> 106 ); 107 }; 108	 109 // these define the screen component styles 110 const styles = stylesheet create({ 111 container { 112 flex 1, 113 backgroundcolor '#fff', 114 }, 115 wrapper { 116 width '90%', 117 alignself 'center', 118 }, 119 header { 120 alignitems 'center', 121 paddingtop 10, 122 paddingbottom 20, 123 backgroundcolor '#208aec', 124 }, 125 header logo { 126 width 170, 127 height 40, 128 marginbottom 10, 129 resizemode 'contain', 130 }, 131 header text bold { 132 color '#fff', 133 fontsize 14, 134 fontweight 'bold', 135 }, 136 header text { 137 margintop 3, 138 color '#fff', 139 fontsize 14, 140 }, 141 form input { 142 height 44, 143 marginbottom 16, 144 backgroundcolor '#fff', 145 fontsize 14, 146 }, 147 switch container { 148 flexdirection 'row', 149 alignitems 'center', 150 justifycontent 'space between', 151 paddingvertical 12, 152 marginbottom 16, 153 borderbottomwidth 1, 154 borderbottomcolor 'rgba(0, 0, 0, 0 3)', 155 }, 156 submit button { 157 width '100%', 158 maxheight 50, 159 alignself 'center', 160 backgroundcolor '#208aec', 161 }, 162 }); 이 화면을 설정한 후, 귀하의 애플리케이션은 다음과 같아야 합니다 각 제품 제품 속성에는 불리언 스위치 입력을 제외하고는 각기 텍스트 입력 필드가 있다는 점에 유의하십시오 이는 저장하기 전에 해당 데이터 유형으로 변환해야 함을 의미합니다 2 입력 데이터 변환 데이터를 parse object parse object , 저장하기 전에 숫자 숫자 , 날짜 및 시간 날짜 및 시간 , 그리고 배열 배열 입력을 올바르게 형식화해야 합니다 이제 상태 변수에서 데이터를 검색하고 적절한 데이터 변환을 적용하는 저장 함수를 만들어 보겠습니다 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 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) { 12 // error can be caused by wrong type of values in fields 13 alert alert('error!', error message); 14 return false; 15 } 16 }; 데이터 숫자 숫자 변환은 값을 숫자 숫자 자바스크립트 객체로 캐스팅하여 수행됩니다 날짜시간 날짜시간 은 날짜 날짜 자바스크립트 객체 생성자를 사용하여 변환됩니다; 배열 배열 은 문자열 분할 문자열 분할 메서드를 사용하여 생성되며, 카테고리 필드의 각 항목이 쉼표로 구분된 배열을 생성합니다 이제 데이터가 단일 객체 안에 포함되어 있으며, 이는 새로운 parse object parse object 인스턴스에 설정되어 서버에 저장될 수 있습니다 이는 parse object set() parse object set() 메서드를 사용하여 수행되며, 이 메서드는 두 개의 인수를 받습니다 필드 이름과 설정할 값입니다 또한 completedata completedata ,라는 새로운 필드를 설정하겠습니다 이는 당신의 객체 객체 유형 필드가 되며, 동일한 데이터 객체를 할당합니다 계속해서 다음과 함께 createproduct createproduct 함수를 완성하세요 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 alert('error!', error message); 14 return false; 15 } 16	 17 // creates a new product parse object instance 18 let product = new parse object('product'); 19 20 // set data to parse object 21 product set('name', productnamevalue); 22 product set('quantity', productquantityvalue); 23 product set('price', productpricevalue); 24 product set('available', productavailablevalue); 25 product set('expirationdate', productexpirationdatevalue); 26 product set('categories', productcategoriesvalue); 27 product set('completedata', { 28 name productnamevalue, 29 quantity productquantityvalue, 30 price productpricevalue, 31 available productavailablevalue, 32 expirationdate productexpirationdatevalue, 33 categories productcategoriesvalue, 34 }); 35	 36 // after setting the values, save it on the server 37 try { 38 let savedproduct = await product save(); 39 // success 40 alert alert('success!', json stringify(savedproduct)); 41 return true; 42 } catch (error) { 43 // error can be caused by lack of internet connection 44 alert 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 } catch (error) { 12 // error can be caused by wrong type of values in fields 13 alert alert('error!', error message); 14 return false; 15 } 16	 17 // creates a new product parse object instance 18 let product parse object = new parse object('product'); 19 20 // set data to parse object 21 product set('name', productnamevalue); 22 product set('quantity', productquantityvalue); 23 product set('price', productpricevalue); 24 product set('available', productavailablevalue); 25 product set('expirationdate', productexpirationdatevalue); 26 product set('categories', productcategoriesvalue); 27 product set('completedata', { 28 name productnamevalue, 29 quantity productquantityvalue, 30 price productpricevalue, 31 available productavailablevalue, 32 expirationdate productexpirationdatevalue, 33 categories productcategoriesvalue, 34 }); 35	 36 // after setting the values, save it on the server 37 try { 38 let savedproduct parse object = await product save(); 39 // success 40 alert alert('success!', json stringify(savedproduct)); 41 return true; 42 } catch (error) { 43 // error can be caused by lack of internet connection 44 alert alert('error!', error message); 45 return false; 46 }; 47 }; 이제 구성 요소를 테스트하고, createproduct createproduct 함수를 삽입한 다음, 양식 제출 버튼 onpress onpress 속성 내에서 호출해야 합니다 제품을 생성한 후에는 다음과 같은 데이터가 포함된 알림을 볼 수 있어야 합니다 서버에 올바른 데이터 유형을 사용하여 데이터가 저장되었음을 인증하려면 parse 대시보드를 확인할 수 있습니다 제품 제품 데이터 테이블을 클릭하고 각 열의 헤더에 데이터 유형이 적혀 있는지 확인하세요 당신의 클래스는 다음과 같아야 합니다 결론 이 가이드의 끝에서, react native 구성 요소를 사용하여 parse에서 사용할 수 있는 각 기본 데이터 유형을 저장하는 방법을 배웠습니다 다음 가이드에서는 parse의 관계형 데이터에 대해 배울 것입니다