React Native
...
Data objects
Data types
10 min
analizzare i tipi di dati in un componente react native introduzione nel cuore della funzionalità parse core c'è la gestione degli oggetti dati parse ti consente di memorizzare e interrogare i suoi dati in modo semplice utilizzando i suoi sdk o api (rest o graphql) tutte le funzionalità degli oggetti dati sono costruite utilizzando la parse object parse object classe, i cui campi possono contenere coppie chiave valore di diversi tipi di dati compatibili con json i tipi di dati principali che possono essere assegnati ai campi dell'oggetto sono i seguenti numero numero numeri interi (42) o numeri in virgola mobile (42 5), purché ‘ ’ sia il separatore decimale; booleano booleano valori true o false; stringa stringa una stringa che può essere lunga fino a 2147483647 caratteri fai attenzione che valori così grandi rallenteranno le operazioni sui dati; dataora dataora dataora dataora oggetti memorizzati in formato utc per impostazione predefinita se hai bisogno di utilizzare un altro fuso orario, la conversione deve essere effettuata manualmente; array array un array contenente dati in qualsiasi formato compatibile con parse oggetto oggetto un oggetto json che contiene anche dati di parse quando disponibile nell'sdk, una include() include() chiamata porterà i dettagli dalla proprietà dell'oggetto quando scegli di utilizzare il tipo array, ti consigliamo di mantenere gli oggetti array piccoli poiché ciò può influenzare le prestazioni complessive delle operazioni sui dati la nostra raccomandazione è di utilizzare il tipo array se non supera i 20 elementi e non cresce nel tempo invece del tipo array, puoi utilizzare i tipi pointer e relations come alternativa in questa guida, imparerai come memorizzare i dati in ciascuno dei tipi di dati di base elencati sopra costruirai un componente di registrazione del prodotto react native, che ti mostrerà come formattare, convertire e salvare i dati nel tuo parse server in react native parse offre anche i tipi di dati geopoint geopoint per utilizzare la potenza delle risorse di geolocalizzazione, e i dati relazionali specifici di parse utilizzando i tipi pointer pointer o relation relation vedrai entrambi trattati nelle prossime guide requisiti per completare questo tutorial, avrai bisogno di un'app react native creata e connessa a https //www back4app com/docs/react native/parse sdk/react native sdk se desideri testare/utilizzare il layout dello schermo fornito da questa guida, dovresti configurare il react native paper react native paper https //github com/callstack/react native paper obiettivo comprendere i tipi di dati di base compatibili con parse e memorizzare ciascun tipo di dato su parse da un componente react native 1 il componente di creazione del prodotto iniziamo a creare la struttura del componente rendiamolo semplice e creiamo una schermata di modulo con un campo di testo per ciascun tipo di dato, un interruttore e un pulsante di invio per salvare l'oggetto questi input raccoglieranno i tuoi prodotto prodotto valori dei campi nome( stringa stringa ), quantità ( numero numero ), prezzo( numero numero ), disponibile( booleano booleano ), data di scadenza( dataora dataora ), e categorie( array array ) inoltre, salverai un campo di tipo oggetto oggetto aggiuntivo nel tuo metodo di salvataggio, ma questo non avrà bisogno di un campo di input crea un componente separato in un file chiamato productcreation js/productcreation tsx productcreation js/productcreation tsx includendo il seguente codice, o aggiungilo al tuo file principale dell'applicazione ( app js/app tsx app js/app tsx o index js index js ) puoi utilizzare questo layout con stili completi usando react native paper react native paper o impostare il tuo modulo personalizzato 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 }); dopo aver impostato questo schermo, la tua applicazione dovrebbe apparire così nota che ogni prodotto prodotto ha il proprio campo di input di testo, tranne per l'input del switch booleano, il che significa che i dati in essi devono essere convertiti nel corrispondente tipo di dato prima di essere salvati 2 conversione dei dati di input prima di salvare i tuoi dati in parse object parse object , è necessario formattare correttamente il numero numero , dataora dataora , e array array input creiamo ora una funzione di salvataggio, che recupererà i dati dalle tue variabili di stato e applicherà la conversione dei dati appropriata 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 }; il numero numero la conversione dei dati avviene convertendo il valore come un numero numero oggetto javascript dataora dataora viene convertito utilizzando il data data costruttore dell'oggetto javascript; il array array viene creato utilizzando il string split string split metodo in javascript, creando un array contenente ogni voce del campo categorie separata da virgole nota che i tuoi dati sono ora contenuti all'interno di un singolo oggetto, che può essere impostato in una nuova parse object parse object istanza da salvare sul server utilizzando il parse object set() parse object set() metodo, che accetta due argomenti il nome del campo e il valore da impostare impostiamo anche un nuovo campo chiamato completedata completedata , che sarà il tuo oggetto oggetto campo di tipo, assegnando lo stesso oggetto dati ad esso vai avanti e completa la createproduct createproduct funzione con il seguente 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 }; ora puoi testare il componente, inserire la createproduct createproduct funzione al suo interno e chiamarla all'interno del pulsante di invio del tuo modulo onpress onpress proprietà dopo aver creato un prodotto, dovresti vedere un avviso contenente i suoi dati come questo per certificare che i tuoi dati siano stati salvati sul server utilizzando i tipi di dati corretti, puoi guardare il tuo dashboard di parse clicca sulla prodotto prodotto tabella dei dati e nota che ogni colonna ha il suo tipo di dato scritto nell'intestazione la tua classe dovrebbe apparire così conclusione alla fine di questa guida, hai imparato come salvare ciascuno dei tipi di dati di base disponibili su parse utilizzando un componente react native nella prossima guida, imparerai sui dati relazionali su parse