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

각 제품 속성에는 불리언 체크박스 입력을 제외하고는 각기 텍스트 입력 필드가 있다는 점에 유의하십시오. 이는 저장하기 전에 해당 데이터 유형으로 변환해야 함을 의미합니다.
2 - 입력 데이터 변환
데이터를 Parse.object, 저장하기 전에 number, DateTime, 및 array 입력을 올바르게 형식화해야 합니다. 이제 상태 변수에서 데이터를 검색하고 적절한 데이터 변환을 적용하는 저장 함수를 만들어 보겠습니다:
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 };숫자 데이터 변환은 값을 로 캐스팅하여 수행됩니다. Number 자바스크립트 객체로. DateTime 은 Date 자바스크립트 객체 생성자를 사용하여 변환됩니다. 배열 하나는 String.split 메서드를 사용하여 생성되며, 카테고리 필드의 각 항목이 쉼표로 구분된 배열을 생성합니다.
당신의 데이터는 이제 단일 객체 안에 포함되어 있으며, 이는 새로운 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
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 };이제 구성 요소를 테스트할 수 있으며, createProduct 함수를 삽입하고, 양식 제출 버튼의 onClick 속성 내에서 호출해야 합니다. 제품을 생성한 후에는 다음과 같은 데이터가 포함된 경고가 표시되어야 합니다:

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

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