React Native
...
Data objects
Basic Queries
11 мин
запрос в react native с использованием parse введение в этом руководстве вы выполните базовые запросы в parse и реализуете компонент react native, используя эти запросы вы узнаете, как настроить и запрашивать реалистичные данные с помощью back4app и react native предварительные требования чтобы завершить это руководство, вам потребуется приложение react native, созданное и подключенное к back4app если вы хотите протестировать/использовать макет экрана, предоставленный в этом руководстве, вам следует настроить react native paper react native paper библиотеку цель запрос данных, хранящихся на back4app, из приложения react native 1 понимание класса parse query любая операция запроса parse использует тип объекта parse query parse query , который поможет вам извлечь конкретные данные из вашей базы данных на протяжении всего вашего приложения важно знать, что parse query parse query разрешится только после вызова метода извлечения (например, parse query find parse query find или parse query get parse query get ), поэтому запрос может быть настроен, и несколько модификаторов могут быть связаны перед фактическим вызовом чтобы создать новый parse query parse query , вам нужно передать в качестве параметра желаемый parse object parse object подкласс, который будет содержать результаты вашего запроса пример запроса можно увидеть ниже, в котором запрашивается вымышленный profile profile подкласс 1 // this will create your query 2 let parsequery = new parse query("profile"); 3 // the query will resolve only after calling this method 4 let queryresult = await parsequery find(); вы можете узнать больше о классе parse query parse query здесь в официальной документации https //parseplatform org/parse sdk js/api/master/parse query html 2 сохраните некоторые данные на back4app давайте создадим класс profile profile , который будет целью наших запросов в этом руководстве в консоли parse js можно выполнять код javascript напрямую, запрашивая и обновляя содержимое вашей базы данных приложения с помощью команд js sdk запустите код ниже из вашей консоли js и вставьте данные на back4app вот как выглядит консоль js на вашей панели управления продолжайте и создайте класс пользователя profile profile с следующим примером содержимого 1 // add profile objects and create table 2 // adam sandler 3 let profile = new parse object('profile'); 4 profile set('name', 'adam sandler'); 5 profile set('birthday', new date('09/09/1966')); 6 profile set('friendcount', 2); 7 profile set('favoritefoods', \['lobster', 'bread']); 8 await profile save(); 9	 10 // adam levine 11 profile = new parse object('profile'); 12 profile set('name', 'adam levine'); 13 profile set('birthday', new date('03/18/1979')); 14 profile set('friendcount', 52); 15 profile set('favoritefoods', \['cake', 'bread']); 16 await profile save(); 17	 18 // carson kressley 19 profile = new parse object('profile'); 20 profile set('name', 'carson kressley'); 21 profile set('birthday', new date('11/11/1969')); 22 profile set('friendcount', 12); 23 profile set('favoritefoods', \['fish', 'cookies']); 24 await profile save(); 25	 26 // dan aykroyd 27 profile = new parse object('profile'); 28 profile set('name', 'dan aykroyd'); 29 profile set('birthday', new date('07/01/1952')); 30 profile set('friendcount', 66); 31 profile set('favoritefoods', \['jam', 'peanut butter']); 32 await profile save(); 33	 34 // eddie murphy 35 profile = new parse object('profile'); 36 profile set('name', 'eddie murphy'); 37 profile set('birthday', new date('04/03/1961')); 38 profile set('friendcount', 49); 39 profile set('favoritefoods', \['lettuce', 'pepper']); 40 await profile save(); 41	 42 // fergie 43 profile = new parse object('profile'); 44 profile set('name', 'fergie'); 45 profile set('birthday', new date('03/27/1975')); 46 profile set('friendcount', 55); 47 profile set('favoritefoods', \['lobster', 'shrimp']); 48 await profile save(); 49	 50 console log('success!'); 3 запрос данных теперь, когда у вас есть заполненный класс, мы можем выполнить некоторые базовые запросы в нем давайте начнем с фильтрации profile profile результатов по имени, которое является полем типа строка, и будем искать значения, содержащие имя адам адам с помощью метода parse query contains parse query contains 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 // `contains` is a basic query method that checks if string field 5 // contains a specific substring 6 parsequery contains('name', 'adam'); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(result get('name')); 16 }; теперь давайте сделаем запрос по полю типа числа friendcount friendcount с использованием другого распространенного метода запроса, parse query greaterthan parse query greaterthan в этом случае мы хотим пользователей profiles profiles с количеством друзей больше 20 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 // `greaterthan` is a basic query method that does what it 5 // says on the tin 6 parsequery greaterthan('friendcount', 20); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(`name ${result get('name')}, friend count ${result get('friendcount')}`); 16 }; другие повторяющиеся методы запроса это parse query ascending parse query ascending и parse query descending parse query descending , отвечающие за упорядочение ваших запросов это упорядочение может быть выполнено для большинства типов данных, поэтому давайте упорядочим запрос по полю даты birthday birthday по самому младшему 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 // `descending` and `ascending` can and should be chained 5 // with other query methods to improve your queries 6 parsequery descending('birthday'); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(`name ${result get('name')}, birthday ${result get('birthday')}`); 16 }; как уже было сказано ранее, вы можете и должны связывать методы запроса, чтобы достичь более точных результатов давайте тогда объединим предыдущие примеры в одном запросе 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 parsequery contains('name', 'adam'); 5 parsequery greaterthan('friendcount', 20); 6 parsequery descending('birthday'); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(`name ${result get('name')}, friend count ${result get('friendcount')}, birthday ${result get('birthday')}`); 16 }; 4 запрос из компонента react native теперь давайте используем наши примерные запросы внутри компонента в react native, с простым интерфейсом, который имеет список, показывающий результаты, и также 4 кнопки для вызова запросов вот как структурирован код компонента, обратите внимание на doquery doquery функции, содержащие примерный код из предыдущего javascript 1 import react, {usestate} from 'react'; 2 import {alert, image, view, scrollview, stylesheet} from 'react native'; 3 import parse from 'parse/react native'; 4 import { 5 list, 6 title, 7 button as paperbutton, 8 text as papertext, 9 } from 'react native paper'; 10	 11 export const booklist = () => { 12 // state variable 13 const \[queryresults, setqueryresults] = usestate(null); 14	 15 const doquerybyname = async function () { 16 // create our parse query instance so methods can be chained 17 // reading parse objects is done by using parse query 18 const parsequery = new parse query('profile'); 19	 20 // `contains` is a basic query method that checks if string field 21 // contains a specific substring 22 parsequery contains('name', 'adam'); 23	 24 try { 25 let profiles = await parsequery find(); 26 setqueryresults(profiles); 27 return true; 28 } catch (error) { 29 // error can be caused by lack of internet connection 30 alert alert('error!', error message); 31 return false; 32 } 33 }; 34	 35 const doquerybyfriendcount = async function () { 36 // create our parse query instance so methods can be chained 37 // reading parse objects is done by using parse query 38 const parsequery = new parse query('profile'); 39	 40 // `greaterthan` is a basic query method that does what it 41 // says on the tin 42 parsequery greaterthan('friendcount', 20); 43	 44 try { 45 let profiles = await parsequery find(); 46 setqueryresults(profiles); 47 return true; 48 } catch (error) { 49 // error can be caused by lack of internet connection 50 alert alert('error!', error message); 51 return false; 52 } 53 }; 54	 55 const doquerybyordering = async function () { 56 // create our parse query instance so methods can be chained 57 // reading parse objects is done by using parse query 58 const parsequery = new parse query('profile'); 59	 60 // `descending` and `ascending` can and should be chained 61 // with other query methods to improve your queries 62 parsequery descending('birthday'); 63	 64 try { 65 let profiles = await parsequery find(); 66 setqueryresults(profiles); 67 return true; 68 } catch (error) { 69 // error can be caused by lack of internet connection 70 alert alert('error!', error message); 71 return false; 72 } 73 }; 74	 75 const doquerybyall = async function () { 76 // create our parse query instance so methods can be chained 77 // reading parse objects is done by using parse query 78 const parsequery = new parse query('profile'); 79	 80 parsequery contains('name', 'adam'); 81 parsequery greaterthan('friendcount', 20); 82 parsequery descending('birthday'); 83	 84 try { 85 let profiles = await parsequery find(); 86 setqueryresults(profiles); 87 return true; 88 } catch (error) { 89 // error can be caused by lack of internet connection 90 alert alert('error!', error message); 91 return false; 92 } 93 }; 94	 95 const clearqueryresults = async function () { 96 setqueryresults(null); 97 return true; 98 }; 99	 100 return ( 101 <> 102 \<view style={styles header}> 103 \<image 104 style={styles header logo} 105 source={ { 106 uri 107 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 108 } } 109 /> 110 \<papertext style={styles header text}> 111 \<papertext style={styles header text bold}> 112 {'react native on back4app '} 113 \</papertext> 114 {' basic queries'} 115 \</papertext> 116 \</view> 117 \<scrollview style={styles wrapper}> 118 \<view> 119 \<title>{'result list'}\</title> 120 {/ book list /} 121 {queryresults !== null && 122 queryresults !== undefined && 123 queryresults map((profile) => ( 124 \<list item 125 key={profile id} 126 title={profile get('name')} 127 description={`friend count ${profile get( 128 'friendcount', 129 )}, birthday ${profile get('birthday')}`} 130 titlestyle={styles list text} 131 style={styles list item} 132 /> 133 ))} 134 {queryresults === null || 135 queryresults === undefined || 136 (queryresults !== null && 137 queryresults !== undefined && 138 queryresults length <= 0) ? ( 139 \<papertext>{'no results here!'}\</papertext> 140 ) null} 141 \</view> 142 \<view> 143 \<title>{'query buttons'}\</title> 144 \<paperbutton 145 onpress={() => doquerybyname()} 146 mode="contained" 147 icon="search web" 148 color={'#208aec'} 149 style={styles list button}> 150 {'query by name'} 151 \</paperbutton> 152 \<paperbutton 153 onpress={() => doquerybyfriendcount()} 154 mode="contained" 155 icon="search web" 156 color={'#208aec'} 157 style={styles list button}> 158 {'query by friend count'} 159 \</paperbutton> 160 \<paperbutton 161 onpress={() => doquerybyordering()} 162 mode="contained" 163 icon="search web" 164 color={'#208aec'} 165 style={styles list button}> 166 {'query by ordering'} 167 \</paperbutton> 168 \<paperbutton 169 onpress={() => doquerybyall()} 170 mode="contained" 171 icon="search web" 172 color={'#208aec'} 173 style={styles list button}> 174 {'query by all'} 175 \</paperbutton> 176 \<paperbutton 177 onpress={() => clearqueryresults()} 178 mode="contained" 179 icon="delete" 180 color={'#208aec'} 181 style={styles list button}> 182 {'clear results'} 183 \</paperbutton> 184 \</view> 185 \</scrollview> 186 \</> 187 ); 188 }; 189	 190 // these define the screen component styles 191 const styles = stylesheet create({ 192 header { 193 alignitems 'center', 194 paddingtop 30, 195 paddingbottom 50, 196 backgroundcolor '#208aec', 197 }, 198 header logo { 199 height 50, 200 width 220, 201 resizemode 'contain', 202 }, 203 header text { 204 margintop 15, 205 color '#f0f0f0', 206 fontsize 16, 207 }, 208 header text bold { 209 color '#fff', 210 fontweight 'bold', 211 }, 212 wrapper { 213 width '90%', 214 alignself 'center', 215 }, 216 list button { 217 margintop 6, 218 marginleft 15, 219 height 40, 220 }, 221 list item { 222 borderbottomwidth 1, 223 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 224 }, 225 list text { 226 fontsize 15, 227 }, 228 });1 import react, {fc, reactelement, usestate} from 'react'; 2 import {alert, image, view, scrollview, stylesheet} from 'react native'; 3 import parse from 'parse/react native'; 4 import { 5 list, 6 title, 7 button as paperbutton, 8 text as papertext, 9 } from 'react native paper'; 10	 11 export const querylist fc<{}> = ({}) reactelement => { 12 // state variable 13 const \[queryresults, setqueryresults] = usestate(null); 14	 15 const doquerybyname = async function () promise\<boolean> { 16 // create our parse query instance so methods can be chained 17 // reading parse objects is done by using parse query 18 const parsequery parse query = new parse query('profile'); 19	 20 // `contains` is a basic query method that checks if string field 21 // contains a specific substring 22 parsequery contains('name', 'adam'); 23	 24 try { 25 let profiles \[parse object] = await parsequery find(); 26 setqueryresults(profiles); 27 return true; 28 } catch (error) { 29 // error can be caused by lack of internet connection 30 alert alert('error!', error message); 31 return false; 32 } 33 }; 34	 35 const doquerybyfriendcount = async function () promise\<boolean> { 36 // create our parse query instance so methods can be chained 37 // reading parse objects is done by using parse query 38 const parsequery parse query = new parse query('profile'); 39	 40 // `greaterthan` is a basic query method that does what it 41 // says on the tin 42 parsequery greaterthan('friendcount', 20); 43	 44 try { 45 let profiles \[parse object] = await parsequery find(); 46 setqueryresults(profiles); 47 return true; 48 } catch (error) { 49 // error can be caused by lack of internet connection 50 alert alert('error!', error message); 51 return false; 52 } 53 }; 54	 55 const doquerybyordering = async function () promise\<boolean> { 56 // create our parse query instance so methods can be chained 57 // reading parse objects is done by using parse query 58 const parsequery parse query = new parse query('profile'); 59	 60 // `descending` and `ascending` can and should be chained 61 // with other query methods to improve your queries 62 parsequery descending('birthday'); 63	 64 try { 65 let profiles \[parse object] = await parsequery find(); 66 setqueryresults(profiles); 67 return true; 68 } catch (error) { 69 // error can be caused by lack of internet connection 70 alert alert('error!', error message); 71 return false; 72 } 73 }; 74	 75 const doquerybyall = async function () promise\<boolean> { 76 // create our parse query instance so methods can be chained 77 // reading parse objects is done by using parse query 78 const parsequery parse query = new parse query('profile'); 79	 80 parsequery contains('name', 'adam'); 81 parsequery greaterthan('friendcount', 20); 82 parsequery descending('birthday'); 83	 84 try { 85 let profiles \[parse object] = await parsequery find(); 86 setqueryresults(profiles); 87 return true; 88 } catch (error) { 89 // error can be caused by lack of internet connection 90 alert alert('error!', error message); 91 return false; 92 } 93 }; 94	 95 const clearqueryresults = async function () promise\<boolean> { 96 setqueryresults(null); 97 return true; 98 }; 99	 100 return ( 101 <> 102 \<view style={styles header}> 103 \<image 104 style={styles header logo} 105 source={ { 106 uri 107 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 108 } } 109 /> 110 \<papertext style={styles header text}> 111 \<papertext style={styles header text bold}> 112 {'react native on back4app '} 113 \</papertext> 114 {' basic queries'} 115 \</papertext> 116 \</view> 117 \<scrollview style={styles wrapper}> 118 \<view> 119 \<title>{'result list'}\</title> 120 {/ book list /} 121 {queryresults !== null && 122 queryresults !== undefined && 123 queryresults map((profile parse object) => ( 124 \<list item 125 key={profile id} 126 title={profile get('name')} 127 description={`friend count ${profile get( 128 'friendcount', 129 )}, birthday ${profile get('birthday')}`} 130 titlestyle={styles list text} 131 style={styles list item} 132 /> 133 ))} 134 {queryresults === null || 135 queryresults === undefined || 136 (queryresults !== null && 137 queryresults !== undefined && 138 queryresults length <= 0) ? ( 139 \<papertext>{'no results here!'}\</papertext> 140 ) null} 141 \</view> 142 \<view> 143 \<title>{'query buttons'}\</title> 144 \<paperbutton 145 onpress={() => doquerybyname()} 146 mode="contained" 147 icon="search web" 148 color={'#208aec'} 149 style={styles list button}> 150 {'query by name'} 151 \</paperbutton> 152 \<paperbutton 153 onpress={() => doquerybyfriendcount()} 154 mode="contained" 155 icon="search web" 156 color={'#208aec'} 157 style={styles list button}> 158 {'query by friend count'} 159 \</paperbutton> 160 \<paperbutton 161 onpress={() => doquerybyordering()} 162 mode="contained" 163 icon="search web" 164 color={'#208aec'} 165 style={styles list button}> 166 {'query by ordering'} 167 \</paperbutton> 168 \<paperbutton 169 onpress={() => doquerybyall()} 170 mode="contained" 171 icon="search web" 172 color={'#208aec'} 173 style={styles list button}> 174 {'query by all'} 175 \</paperbutton> 176 \<paperbutton 177 onpress={() => clearqueryresults()} 178 mode="contained" 179 icon="delete" 180 color={'#208aec'} 181 style={styles list button}> 182 {'clear results'} 183 \</paperbutton> 184 \</view> 185 \</scrollview> 186 \</> 187 ); 188 }; 189	 190 // these define the screen component styles 191 const styles = stylesheet create({ 192 header { 193 alignitems 'center', 194 paddingtop 30, 195 paddingbottom 50, 196 backgroundcolor '#208aec', 197 }, 198 header logo { 199 height 50, 200 width 220, 201 resizemode 'contain', 202 }, 203 header text { 204 margintop 15, 205 color '#f0f0f0', 206 fontsize 16, 207 }, 208 header text bold { 209 color '#fff', 210 fontweight 'bold', 211 }, 212 wrapper { 213 width '90%', 214 alignself 'center', 215 }, 216 list button { 217 margintop 6, 218 marginleft 15, 219 height 40, 220 }, 221 list item { 222 borderbottomwidth 1, 223 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 224 }, 225 list text { 226 fontsize 15, 227 }, 228 }); вот как компонент должен выглядеть после рендеринга и запроса с помощью всех функций запроса заключение в конце этого руководства вы узнали, как работают базовые запросы данных на parse и как выполнять их на back4app из приложения react native в следующем руководстве вы исследуете parse query parse query в полном объеме, используя все методы, доступные в этом классе