Использование Parse в React для базового запроса данных
11 мин
запрос в react с использованием parse введение в этом руководстве вы выполните базовые запросы в parse и реализуете компонент react, используя эти запросы вы узнаете, как настроить и запрашивать реалистичные данные с помощью back4app и react предварительные условия чтобы завершить этот учебник, вам потребуется приложение react, созданное и подключенное к back4app https //www back4app com/docs/react/quickstart если вы хотите запустить пример проекта из этого руководства, вам следует установить библиотеку https //ant design/ цель запрос данных, хранящихся на back4app, из приложения react 1 понимание класса parse query любая операция запроса parse использует тип объекта \<font color="#2166ae">parse query\</font> , который поможет вам извлекать конкретные данные из вашей базы данных на протяжении всего приложения важно знать, что \<font color="#2166ae">parse query\</font> будет разрешен только после вызова метода извлечения (например, \<font color="#2166ae">parse query find \</font> или \<font color="#2166ae">parse query get\</font> ), поэтому запрос может быть настроен, и несколько модификаторов могут быть связаны перед фактическим вызовом чтобы создать новый \<font color="#2166ae">parse query\</font> , вам нужно передать в качестве параметра желаемый \<font color="#2166ae">parse object\</font> подкласс, который будет содержать результаты вашего запроса пример запроса можно увидеть ниже, в котором запрашивается вымышленный \<font color="#2166ae">profile \</font> подкласс 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(); вы можете узнать больше о классе \<font color="#2166ae">parse query\</font> здесь в официальной документации https //parseplatform org/parse sdk js/api/master/parse query html 2 сохраните некоторые данные на back4app давайте создадим класс \<font color="#2166ae">profile \</font> , который будет целью наших запросов в этом руководстве в консоли parse js можно выполнять код javascript напрямую, запрашивая и обновляя содержимое базы данных вашего приложения с помощью команд js sdk запустите код ниже из вашей js консоли и вставьте данные на back4app вот как выглядит консоль js на вашей панели продолжайте и создайте класс пользователя \<font color="#2166ae">профиль\</font> с следующим примером содержимого 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 запрос данных теперь, когда у вас есть заполненный класс, мы можем выполнить несколько основных запросов в нем давайте начнем с фильтрации \<font color="#2166ae">профиль \</font> результатов по имени, которое является полем строкового типа, и будем искать значения, содержащие имя \<font color="#2166ae">адам \</font> с помощью метода \<font color="#2166ae">parse query contains\</font> 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 }; теперь давайте запросим по полю числового типа \<font color="#2166ae">friendcount \</font> с помощью другого распространенного метода запроса, \<font color="#2166ae">parse query greaterthan\</font> в этом случае мы хотим пользователей \<font color="#2166ae">профили \</font> с количеством друзей больше 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 }; другие повторяющиеся методы запроса это \<font color="#2166ae">parse query ascending\</font> и \<font color="#2166ae">parse query descending\</font> , отвечающие за упорядочение ваших запросов это упорядочение может быть выполнено для большинства типов данных, так что давайте упорядочим запрос по полю даты \<font color="#2166ae">birthday \</font> по самому младшему 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 теперь давайте используем наши примерные запросы внутри компонента в react, с простым интерфейсом, имеющим список, показывающий результаты, и также 4 кнопки для вызова запросов вот как выглядит код компонента, обратите внимание на \<font color="#2166ae">doquery \</font> функции, содержащие примерный код из предыдущего javascript 1 import react, { usestate } from 'react'; 2 import parse from 'parse/dist/parse min js'; 3 import ' /app css'; 4 import { button, divider } from 'antd'; 5 import { closeoutlined, searchoutlined } from '@ant design/icons'; 6	 7 export const querybasic = () => { 8 // state variable 9 const \[queryresults, setqueryresults] = usestate(); 10	 11 const doquerybyname = async function () { 12 // create our parse query instance so methods can be chained 13 // reading parse objects is done by using parse query 14 const parsequery = new parse query('profile'); 15	 16 // `contains` is a basic query method that checks if string field 17 // contains a specific substring 18 parsequery contains('name', 'adam'); 19	 20 try { 21 let profiles = await parsequery find(); 22 setqueryresults(profiles); 23 return true; 24 } catch (error) { 25 // error can be caused by lack of internet connection 26 alert(`error! ${error message}`); 27 return false; 28 } 29 }; 30	 31 const doquerybyfriendcount = async function () { 32 // create our parse query instance so methods can be chained 33 // reading parse objects is done by using parse query 34 const parsequery = new parse query('profile'); 35	 36 // `greaterthan` is a basic query method that does what it 37 // says on the tin 38 parsequery greaterthan('friendcount', 20); 39	 40 try { 41 let profiles = await parsequery find(); 42 setqueryresults(profiles); 43 return true; 44 } catch (error) { 45 // error can be caused by lack of internet connection 46 alert(`error! ${error message}`); 47 return false; 48 } 49 }; 50	 51 const doquerybyordering = async function () { 52 // create our parse query instance so methods can be chained 53 // reading parse objects is done by using parse query 54 const parsequery = new parse query('profile'); 55	 56 // `descending` and `ascending` can and should be chained 57 // with other query methods to improve your queries 58 parsequery descending('birthday'); 59	 60 try { 61 let profiles = await parsequery find(); 62 setqueryresults(profiles); 63 return true; 64 } catch (error) { 65 // error can be caused by lack of internet connection 66 alert(`error! ${error message}`); 67 return false; 68 } 69 }; 70	 71 const doquerybyall = async function () { 72 // create our parse query instance so methods can be chained 73 // reading parse objects is done by using parse query 74 const parsequery = new parse query('profile'); 75	 76 parsequery contains('name', 'adam'); 77 parsequery greaterthan('friendcount', 20); 78 parsequery descending('birthday'); 79	 80 try { 81 let profiles = await parsequery find(); 82 setqueryresults(profiles); 83 return true; 84 } catch (error) { 85 // error can be caused by lack of internet connection 86 alert(`error! ${error message}`); 87 return false; 88 } 89 }; 90	 91 const clearqueryresults = async function () { 92 setqueryresults(undefined); 93 return true; 94 }; 95	 96 return ( 97 \<div> 98 \<div classname="header"> 99 \<img 100 classname="header logo" 101 alt="back4app logo" 102 src={ 103 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 104 } 105 /> 106 \<p classname="header text bold">{'react on back4app'}\</p> 107 \<p classname="header text">{'basic queries'}\</p> 108 \</div> 109 \<div classname="container"> 110 \<div classname="flex between"> 111 \<h2 classname="heading">{'query list'}\</h2> 112 \<div classname="flex"> 113 \<button 114 onclick={() => doquerybyname()} 115 type="primary" 116 classname="heading button" 117 color={'#208aec'} 118 icon={\<searchoutlined />} 119 > 120 by name 121 \</button> 122 \<button 123 onclick={() => doquerybyfriendcount()} 124 type="primary" 125 classname="heading button" 126 color={'#208aec'} 127 icon={\<searchoutlined />} 128 > 129 by friend count 130 \</button> 131 \<button 132 onclick={() => doquerybyordering()} 133 type="primary" 134 classname="heading button" 135 color={'#208aec'} 136 icon={\<searchoutlined />} 137 > 138 by ordering 139 \</button> 140 \<button 141 onclick={() => doquerybyall()} 142 type="primary" 143 classname="heading button" 144 color={'#208aec'} 145 icon={\<searchoutlined />} 146 > 147 by all 148 \</button> 149 \<button 150 onclick={() => clearqueryresults()} 151 type="primary" 152 classname="heading button" 153 color={'#208aec'} 154 icon={\<closeoutlined />} 155 > 156 clear 157 \</button> 158 \</div> 159 \</div> 160 \<divider /> 161 \<div classname="flex between"> 162 \<div classname="flex child"> 163 {/ query list /} 164 {queryresults !== undefined && 165 queryresults map((profile, index) => ( 166 \<div classname="list item" key={`${index}`}> 167 \<p classname="list item title">{`${profile get('name')}`}\</p> 168 \<p classname="list item description">{`friend count ${profile get( 169 'friendcount' 170 )}, birthday ${profile get('birthday')}`}\</p> 171 \</div> 172 ))} 173 {queryresults !== undefined && queryresults length <= 0 ? ( 174 \<p>{'no results here!'}\</p> 175 ) null} 176 \</div> 177 \</div> 178 \</div> 179 \</div> 180 ); 181 }; typescript 1 import react, { usestate, fc, reactelement } from 'react'; 2 import ' /app css'; 3 import { button, divider } from 'antd'; 4 import { closeoutlined, searchoutlined } from '@ant design/icons'; 5 const parse = require('parse/dist/parse min js'); 6	 7 export const querybasic fc<{}> = () reactelement => { 8 // state variable 9 const \[queryresults, setqueryresults] = usestate\<parse object\[]>(); 10	 11 const doquerybyname = async function () promise\<boolean> { 12 // create our parse query instance so methods can be chained 13 // reading parse objects is done by using parse query 14 const parsequery parse query = new parse query('profile'); 15	 16 // `contains` is a basic query method that checks if string field 17 // contains a specific substring 18 parsequery contains('name', 'adam'); 19	 20 try { 21 let profiles parse object\[] = await parsequery find(); 22 setqueryresults(profiles); 23 return true; 24 } catch (error any) { 25 // error can be caused by lack of internet connection 26 alert(`error! ${error message}`); 27 return false; 28 } 29 }; 30	 31 const doquerybyfriendcount = async function () promise\<boolean> { 32 // create our parse query instance so methods can be chained 33 // reading parse objects is done by using parse query 34 const parsequery parse query = new parse query('profile'); 35	 36 // `greaterthan` is a basic query method that does what it 37 // says on the tin 38 parsequery greaterthan('friendcount', 20); 39	 40 try { 41 let profiles parse object\[] = await parsequery find(); 42 setqueryresults(profiles); 43 return true; 44 } catch (error any) { 45 // error can be caused by lack of internet connection 46 alert(`error! ${error message}`); 47 return false; 48 } 49 }; 50	 51 const doquerybyordering = async function () promise\<boolean> { 52 // create our parse query instance so methods can be chained 53 // reading parse objects is done by using parse query 54 const parsequery parse query = new parse query('profile'); 55	 56 // `descending` and `ascending` can and should be chained 57 // with other query methods to improve your queries 58 parsequery descending('birthday'); 59	 60 try { 61 let profiles parse object\[] = await parsequery find(); 62 setqueryresults(profiles); 63 return true; 64 } catch (error any) { 65 // error can be caused by lack of internet connection 66 alert(`error! ${error message}`); 67 return false; 68 } 69 }; 70	 71 const doquerybyall = async function () promise\<boolean> { 72 // create our parse query instance so methods can be chained 73 // reading parse objects is done by using parse query 74 const parsequery parse query = new parse query('profile'); 75	 76 parsequery contains('name', 'adam'); 77 parsequery greaterthan('friendcount', 20); 78 parsequery descending('birthday'); 79	 80 try { 81 let profiles parse object\[] = await parsequery find(); 82 setqueryresults(profiles); 83 return true; 84 } catch (error any) { 85 // error can be caused by lack of internet connection 86 alert(`error! ${error message}`); 87 return false; 88 } 89 }; 90	 91 const clearqueryresults = async function () promise\<boolean> { 92 setqueryresults(undefined); 93 return true; 94 }; 95	 96 return ( 97 \<div> 98 \<div classname="header"> 99 \<img 100 classname="header logo" 101 alt="back4app logo" 102 src={ 103 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 104 } 105 /> 106 \<p classname="header text bold">{'react on back4app'}\</p> 107 \<p classname="header text">{'basic queries'}\</p> 108 \</div> 109 \<div classname="container"> 110 \<div classname="flex between"> 111 \<h2 classname="heading">{'query list'}\</h2> 112 \<div classname="flex"> 113 \<button 114 onclick={() => doquerybyname()} 115 type="primary" 116 classname="heading button" 117 color={'#208aec'} 118 icon={\<searchoutlined />} 119 > 120 by name 121 \</button> 122 \<button 123 onclick={() => doquerybyfriendcount()} 124 type="primary" 125 classname="heading button" 126 color={'#208aec'} 127 icon={\<searchoutlined />} 128 > 129 by friend count 130 \</button> 131 \<button 132 onclick={() => doquerybyordering()} 133 type="primary" 134 classname="heading button" 135 color={'#208aec'} 136 icon={\<searchoutlined />} 137 > 138 by ordering 139 \</button> 140 \<button 141 onclick={() => doquerybyall()} 142 type="primary" 143 classname="heading button" 144 color={'#208aec'} 145 icon={\<searchoutlined />} 146 > 147 by all 148 \</button> 149 \<button 150 onclick={() => clearqueryresults()} 151 type="primary" 152 classname="heading button" 153 color={'#208aec'} 154 icon={\<closeoutlined />} 155 > 156 clear 157 \</button> 158 \</div> 159 \</div> 160 \<divider /> 161 \<div classname="flex between"> 162 \<div classname="flex child"> 163 {/ query list /} 164 {queryresults !== undefined && 165 queryresults map((profile parse object, index number) => ( 166 \<div classname="list item" key={`${index}`}> 167 \<p classname="list item title">{`${profile get('name')}`}\</p> 168 \<p classname="list item description">{`friend count ${profile get( 169 'friendcount' 170 )}, birthday ${profile get('birthday')}`}\</p> 171 \</div> 172 ))} 173 {queryresults !== undefined && 174 queryresults length <= 0 ? ( 175 \<p>{'no results here!'}\</p> 176 ) null} 177 \</div> 178 \</div> 179 \</div> 180 \</div> 181 ); 182 }; также добавьте эти классы в ваш \<font color="#2166ae">app css\</font> файл, чтобы правильно отобразить все элементы интерфейса 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 font weight bold; 23 } 24 25 p { 26 margin 0; 27 } 28 29 body { 30 margin 0; 31 background color #fff; 32 } 33 34 container { 35 width 100%; 36 max width 900px; 37 margin auto; 38 padding 20px 0; 39 text align left; 40 } 41 42 header { 43 align items center; 44 padding 25px 0; 45 background color #208aec; 46 } 47 48 header logo { 49 height 55px; 50 margin bottom 20px; 51 object fit contain; 52 } 53 54 header text bold { 55 margin bottom 3px; 56 color rgba(255, 255, 255, 0 9); 57 font size 16px; 58 font weight bold; 59 } 60 61 header text { 62 color rgba(255, 255, 255, 0 9); 63 font size 15px; 64 } 65 66 heading { 67 font size 22px; 68 } 69 70 flex { 71 display flex; 72 } 73 74 flex between { 75 display flex; 76 justify content space between; 77 } 78 79 flex child { 80 flex 0 0 45%; 81 } 82 83 heading button { 84 margin left 12px; 85 } 86 87 list item { 88 padding bottom 15px; 89 margin bottom 15px; 90 border bottom 1px solid rgba(0,0,0,0 06); 91 text align left; 92 } 93 94 list item title { 95 color rgba(0,0,0,0 87); 96 font size 17px; 97 } 98 99 list item description { 100 color rgba(0,0,0,0 5); 101 font size 15px; 102 } вот как компонент должен выглядеть после рендеринга и запроса с помощью всех функций запроса заключение в конце этого руководства вы узнали, как работают базовые запросы данных на parse и как выполнять их на back4app из react приложения в следующем руководстве вы исследуете \<font color="#2166ae">parse query\</font> в полном объеме, используя все методы, доступные в этом классе