Data types
리액트 네이티브 컴포넌트에서 데이터 유형 파싱
소개
Parse Core 기능의 핵심은 데이터 객체 관리입니다. Parse는 SDK 또는 API(REST 또는 GraphQL)를 사용하여 데이터를 간단하게 저장하고 쿼리할 수 있도록 합니다. 모든 데이터 객체 기능은 Parse.Object 클래스를 사용하여 구축되며, 이 클래스의 필드는 여러 JSON 호환 데이터 유형의 키-값 쌍을 포함할 수 있습니다. 객체 필드에 할당할 수 있는 주요 데이터 유형은 다음과 같습니다:
- 숫자: 정수(42) 또는 부동 소수점(42.5) 숫자, ‘.’가 소수 구분 기호인 경우;
- 부울: true 또는 false 값;
- 문자열: 최대 2147483647자까지의 문자열. 이렇게 큰 값은 데이터 작업을 느리게 할 수 있습니다;
- 날짜 및 시간:날짜 및 시간 객체는 기본적으로 UTC 형식으로 저장됩니다. 다른 시간대를 사용해야 하는 경우 수동으로 변환해야 합니다;
- 배열: Parse와 호환되는 데이터가 포함된 배열.
- 객체: JSON 객체로, Parse 데이터도 포함됩니다. SDK에서 사용할 수 있을 때, include() 호출은 객체 속성의 세부 정보를 가져옵니다.
Array 유형을 사용하기로 선택할 때, 배열 객체를 작게 유지하는 것이 좋습니다. 이는 데이터 작업의 전반적인 성능에 영향을 미칠 수 있습니다. 20개 요소를 초과하지 않고 시간이 지남에 따라 증가하지 않는 경우 Array 유형을 사용하는 것이 좋습니다. Array 유형 대신 Pointer 및 Relation 유형을 대안으로 사용할 수 있습니다.
이 가이드에서는 위에 나열된 각 기본 데이터 유형에 데이터를 저장하는 방법을 배웁니다. React Native 제품 등록 구성 요소를 구축하여 데이터를 형식화, 변환 및 Parse Server에 저장하는 방법을 보여줍니다.
Parse는 또한 지리적 위치 리소스의 힘을 사용하기 위해 GeoPoint와 Pointer 또는 Relation을 사용하여 Parse 전용 관계형 데이터를 제공합니다. 다음 가이드에서 두 가지 모두 다룰 것입니다.
전제 조건
목표
Parse와 호환되는 기본 데이터 유형을 이해하고, React Native 구성 요소에서 각 데이터 유형을 Parse에 저장하는 것입니다.
1 - 제품 생성 구성 요소
먼저 구성 요소 구조를 생성해 보겠습니다. 간단하게 만들고 각 데이터 유형에 대해 하나의 텍스트 입력, 하나의 스위치 토글, 그리고 객체를 저장하기 위한 제출 버튼이 있는 양식 화면을 만듭니다. 이러한 입력은 다음과 같은 제품 필드 값을 수집합니다: 이름(문자열), 수량(숫자), 가격(숫자), 사용 가능(부울), 만료 날짜(날짜 및 시간), 및 카테고리(배열). 또한, 저장 방법에서 추가 객체 유형 필드를 저장할 것이지만, 이 필드는 입력 필드가 필요하지 않습니다.
다음 코드를 포함하여 ProductCreation.js/ProductCreation.tsx라는 파일에 별도의 컴포넌트를 생성하거나, 주요 애플리케이션 파일(App.js/App.tsx 또는 index.js)에 추가하세요. react-native-paper를 사용하여 완전한 스타일링으로 이 레이아웃을 사용할 수 있거나, 사용자 정의 양식을 설정할 수 있습니다.
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 });이 화면을 설정한 후, 귀하의 애플리케이션은 다음과 같아야 합니다:

각 제품 속성에는 불리언 스위치 입력을 제외하고는 각기 텍스트 입력 필드가 있다는 점에 유의하십시오. 이는 저장하기 전에 해당 데이터 유형으로 변환해야 함을 의미합니다.
2 - 입력 데이터 변환
데이터를 Parse.object, 저장하기 전에 숫자, 날짜 및 시간, 그리고 배열 입력을 올바르게 형식화해야 합니다. 이제 상태 변수에서 데이터를 검색하고 적절한 데이터 변환을 적용하는 저장 함수를 만들어 보겠습니다:
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.set() 메서드를 사용하여 수행되며, 이 메서드는 두 개의 인수를 받습니다: 필드 이름과 설정할 값입니다. 또한 completeData,라는 새로운 필드를 설정하겠습니다. 이는 당신의 객체 유형 필드가 되며, 동일한 데이터 객체를 할당합니다.
계속해서 다음과 함께 createProduct 함수를 완성하세요:
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 함수를 삽입한 다음, 양식 제출 버튼 onPress 속성 내에서 호출해야 합니다. 제품을 생성한 후에는 다음과 같은 데이터가 포함된 알림을 볼 수 있어야 합니다:

서버에 올바른 데이터 유형을 사용하여 데이터가 저장되었음을 인증하려면 Parse 대시보드를 확인할 수 있습니다. 제품 데이터 테이블을 클릭하고 각 열의 헤더에 데이터 유형이 적혀 있는지 확인하세요. 당신의 클래스는 다음과 같아야 합니다:

결론
이 가이드의 끝에서, React Native 구성 요소를 사용하여 Parse에서 사용할 수 있는 각 기본 데이터 유형을 저장하는 방법을 배웠습니다. 다음 가이드에서는 Parse의 관계형 데이터에 대해 배울 것입니다.