React Native
...
Users
Вход и выход: React Native с Parse SDK
20 мин
вход и выход пользователя для react native введение после реализации компонента, который обрабатывает регистрацию пользователей в parse в последнем руководстве, вы теперь узнаете, как входить и выходить из системы с помощью того же parse user parse user класса вы также научитесь устанавливать и настраивать react navigation react navigation чтобы вы могли перемещать пользователя по вашим новым экранам и компонентам метод parse user login parse user login сохраняет в вашем локальном хранилище действительную сессию пользователя, так что будущие вызовы методов, таких как currentasync currentasync успешно извлекут ваши данные пользователя с другой стороны, logout logout очистит эту сессию с диска и выйдет из любых связанных сервисов на вашем сервере parse в любое время вы можете получить доступ к полному проекту android, созданному с помощью этого руководства, в наших репозиториях на github репозиторий примера на kotlin репозиторий примера на java предварительные требования чтобы завершить это руководство, вам потребуется приложение react native, созданное и подключенное к back4app пройдите предыдущие руководства, чтобы лучше понять класс пользователя parse цель создание функции входа и выхода пользователя с использованием parse для приложения react native 1 установка зависимостей в какой то момент каждое приложение на react native нуждается в навигации по экранам теперь вы узнаете, как установить и настроить самую используемую библиотеку в react native для этого, react navigation react navigation перейдите в корневую директорию вашего проекта и установите следующие зависимости если вы разрабатываете для ios, вам нужно установить pods, чтобы завершить автоматическую привязку вашего приложения примечание привязка автоматическая для react native 0 60+ 0 60+ для всех платформ, поэтому, если вы все еще используете более старую версию rn, посмотрите документацию react native здесь https //reactnative dev/docs/linking libraries ios в вашем файле входа приложения ( app tsx app tsx или app js app js ), добавьте эту строку импорта в самом верху файла теперь вам нужно переместить ваши компоненты внутрь react navigation react navigation контейнера, который будет инкапсулировать ваше приложение внутри navigationcontainer navigationcontainer app tsx/app js 1 import "react native gesture handler"; 2 // your other imports go here 3 import { navigationcontainer } from "@react navigation/native"; 4	 5 const app = () => { 6 return \<navigationcontainer>{/ your app code /}\</navigationcontainer>; 7 } 8	 9 export default app; основная библиотека навигации имеет различные дополнительные модули навигации, такие как стек, вкладки, ящик и другие навигатор стека является самым простым и тем, который вы будете использовать в этом руководстве продолжайте с установкой 2 создание stacknavigator теперь давайте создадим и настроим stacknavigator stacknavigator этот модуль будет управлять и обрабатывать навигацию по экранам в вашем приложении поскольку здесь не ставится цель дать вам глубокое понимание react navigation глубокое понимание react navigation , пожалуйста, перейдите к официальной документации https //reactnavigation org/docs/hello react navigation/ , чтобы узнать больше в вашем app js app js ( app tsx app tsx если вы используете typescript) файле, импортируйте и создайте stacknavigator stacknavigator , создайте функцию, содержащую экран регистрации пользователя, и вставьте навигатор внутрь вашего приложения navigationcontainer navigationcontainer ваш основной файл должен выглядеть так app tsx/app js 1 import 'react native gesture handler'; 2 import react from 'react'; 3 import {image, safeareaview, statusbar, text, view} from 'react native'; 4	 5 import asyncstorage from '@react native async storage/async storage'; 6 import parse from 'parse/react native'; 7 import {navigationcontainer} from '@react navigation/native'; 8 import {createstacknavigator} from '@react navigation/stack'; 9 import {userregistration} from ' /userregistration'; 10 import styles from ' /styles'; 11	 12 // your parse initialization configuration goes here 13 parse setasyncstorage(asyncstorage); 14 const parse application id string = 'application id'; 15 const parse host url string = 'host url'; 16 const parse javascript id string = 'javascript id'; 17 parse initialize(parse application id, parse javascript id); 18 parse serverurl = parse host url; 19	 20 // wrap your old app screen in a separate function, so you can create a screen 21 // inside the navigator; you can also declare your screens in a separate file, 22 // export and import here to reduce some clutter 23 function userregistrationscreen() { 24 return ( 25 <> 26 \<statusbar /> 27 \<safeareaview style={styles login container}> 28 \<view style={styles login header}> 29 \<image 30 style={styles login header logo} 31 source={require(' /assets/logo back4app png')} 32 /> 33 \<text style={styles login header text}> 34 \<text style={styles login header text bold}> 35 {'react native on back4app '} 36 \</text> 37 {' user registration'} 38 \</text> 39 \</view> 40 \<userregistration /> 41 \</safeareaview> 42 \</> 43 ); 44 } 45	 46 // create your main navigator here 47 const stack = createstacknavigator(); 48	 49 // add the stack navigator to your navigationcontainer 50 // and in it you can add all your app screens in the order you need 51 // them on your stack 52 const app = () => { 53 return ( 54 \<navigationcontainer> 55 \<stack navigator> 56 \<stack screen name="sign up" component={userregistrationscreen} /> 57 \</stack navigator> 58 \</navigationcontainer> 59 ); 60 }; 61	 62 export default app; если вы запустите свое приложение сейчас, вы заметите наличие заголовка в верхней части экрана, содержащего ваше имя экрана 3 создание компонента входа в систему теперь давайте создадим userlogin userlogin функциональный компонент в вашем приложении создайте новый файл в корневом каталоге с именем userlogin js userlogin js ( userlogin tsx userlogin tsx если вы используете typescript) и добавьте элементы ввода, используя хуки состояния для управления их данными userlogin js 1 import react, {fc, reactelement, usestate} from 'react'; 2 import { 3 image, 4 text, 5 textinput, 6 touchableopacity, 7 view, 8 } from 'react native'; 9 import parse from 'parse/react native'; 10 import styles from ' /styles'; 11	 12 export const userlogin = () => { 13 const \[username, setusername] = usestate(""); 14 const \[password, setpassword] = usestate(""); 15	 16 return ( 17 \<view style={styles login wrapper}> 18 \<view style={styles form}> 19 \<textinput 20 style={styles form input} 21 value={username} 22 placeholder={'username'} 23 onchangetext={(text) => setusername(text)} 24 autocapitalize={'none'} 25 keyboardtype={'email address'} 26 /> 27 \<textinput 28 style={styles form input} 29 value={password} 30 placeholder={'password'} 31 securetextentry 32 onchangetext={(text) => setpassword(text)} 33 /> 34 \<touchableopacity onpress={() => {}}> 35 \<view style={styles button}> 36 \<text style={styles button label}>{'sign in'}\</text> 37 \</view> 38 \</touchableopacity> 39 \</view> 40 \<view style={styles login social}> 41 \<view style={styles login social separator}> 42 \<view style={styles login social separator line} /> 43 \<text style={styles login social separator text}>{'or'}\</text> 44 \<view style={styles login social separator line} /> 45 \</view> 46 \<view style={styles login social buttons}> 47 \<touchableopacity> 48 \<view 49 style={\[ 50 styles login social button, 51 styles login social facebook, 52 ]}> 53 \<image 54 style={styles login social icon} 55 source={require(' /assets/icon facebook png')} 56 /> 57 \</view> 58 \</touchableopacity> 59 \<touchableopacity> 60 \<view style={styles login social button}> 61 \<image 62 style={styles login social icon} 63 source={require(' /assets/icon google png')} 64 /> 65 \</view> 66 \</touchableopacity> 67 \<touchableopacity> 68 \<view style={styles login social button}> 69 \<image 70 style={styles login social icon} 71 source={require(' /assets/icon apple png')} 72 /> 73 \</view> 74 \</touchableopacity> 75 \</view> 76 \</view> 77 \</view> 78 ); 79 }; userlogin tsx 1 import react, {fc, reactelement, usestate} from 'react'; 2 import { 3 image, 4 text, 5 textinput, 6 touchableopacity, 7 view, 8 } from 'react native'; 9 import parse from 'parse/react native'; 10 import styles from ' /styles'; 11	 12 export const userlogin fc<{}> = ({}) reactelement => { 13 const \[username, setusername] = usestate(""); 14 const \[password, setpassword] = usestate(""); 15	 16 return ( 17 \<view style={styles login wrapper}> 18 \<view style={styles form}> 19 \<textinput 20 style={styles form input} 21 value={username} 22 placeholder={'username'} 23 onchangetext={(text) => setusername(text)} 24 autocapitalize={'none'} 25 keyboardtype={'email address'} 26 /> 27 \<textinput 28 style={styles form input} 29 value={password} 30 placeholder={'password'} 31 securetextentry 32 onchangetext={(text) => setpassword(text)} 33 /> 34 \<touchableopacity onpress={() => {}}> 35 \<view style={styles button}> 36 \<text style={styles button label}>{'sign in'}\</text> 37 \</view> 38 \</touchableopacity> 39 \</view> 40 \<view style={styles login social}> 41 \<view style={styles login social separator}> 42 \<view style={styles login social separator line} /> 43 \<text style={styles login social separator text}>{'or'}\</text> 44 \<view style={styles login social separator line} /> 45 \</view> 46 \<view style={styles login social buttons}> 47 \<touchableopacity> 48 \<view 49 style={\[ 50 styles login social button, 51 styles login social facebook, 52 ]}> 53 \<image 54 style={styles login social icon} 55 source={require(' /assets/icon facebook png')} 56 /> 57 \</view> 58 \</touchableopacity> 59 \<touchableopacity> 60 \<view style={styles login social button}> 61 \<image 62 style={styles login social icon} 63 source={require(' /assets/icon google png')} 64 /> 65 \</view> 66 \</touchableopacity> 67 \<touchableopacity> 68 \<view style={styles login social button}> 69 \<image 70 style={styles login social icon} 71 source={require(' /assets/icon apple png')} 72 /> 73 \</view> 74 \</touchableopacity> 75 \</view> 76 \</view> 77 \</view> 78 ); 79 }; теперь вы можете реализовать функцию, которая вызовет метод parse user login parse user login , используя переменные состояния javascript 1 const douserlogin = async function () { 2 // note that these values come from state variables that we've declared before 3 const usernamevalue = username; 4 const passwordvalue = password; 5 return await parse user login(usernamevalue, passwordvalue) 6 then(async (loggedinuser) => { 7 // login returns the corresponding parseuser object 8 alert alert( 9 'success!', 10 `user ${loggedinuser get('username')} has successfully signed in!`, 11 ); 12 // to verify that this is in fact the current user, currentasync can be used 13 const currentuser = await parse user currentasync(); 14 console log(loggedinuser === currentuser); 15 return true; 16 }) 17 catch((error) => { 18 // error can be caused by wrong parameters or lack of internet connection 19 alert alert('error!', error message); 20 return false; 21 }); 22 };1 const douserlogin = async function () promise\<boolean> { 2 // note that these values come from state variables that we've declared before 3 const usernamevalue string = username; 4 const passwordvalue string = password; 5 return await parse user login(usernamevalue, passwordvalue) 6 then(async (loggedinuser parse user) => { 7 // login returns the corresponding parseuser object 8 alert alert( 9 'success!', 10 `user ${loggedinuser get('username')} has successfully signed in!`, 11 ); 12 // to verify that this is in fact the current user, currentasync can be used 13 const currentuser parse user = await parse user currentasync(); 14 console log(loggedinuser === currentuser); 15 return true; 16 }) 17 catch((error object) => { 18 // error can be caused by wrong parameters or lack of internet connection 19 alert alert('error!', error message); 20 return false; 21 }); 22 }; вставьте эту функцию внутрь userlogin userlogin компонента, сразу перед return return вызовом, чтобы ее можно было вызвать и протестировать не забудьте обновить действие кнопки входа формы onpress onpress на () => douserlogin() () => douserlogin() и импортировать alert alert из react native react native ваш компонент теперь должен выглядеть так userlogin js 1 import react, {fc, reactelement, usestate} from 'react'; 2 import { 3 alert, 4 image, 5 text, 6 textinput, 7 touchableopacity, 8 view, 9 } from 'react native'; 10 import parse from 'parse/react native'; 11 import styles from ' /styles'; 12	 13 export const userlogin = () => { 14 const \[username, setusername] = usestate(''); 15 const \[password, setpassword] = usestate(''); 16	 17 const douserlogin = async function () { 18 // note that these values come from state variables that we've declared before 19 const usernamevalue = username; 20 const passwordvalue = password; 21 return await parse user login(usernamevalue, passwordvalue) 22 then(async (loggedinuser) => { 23 // login returns the corresponding parseuser object 24 alert alert( 25 'success!', 26 `user ${loggedinuser get('username')} has successfully signed in!`, 27 ); 28 // to verify that this is in fact the current user, currentasync can be used 29 const currentuser = await parse user currentasync(); 30 console log(loggedinuser === currentuser); 31 return true; 32 }) 33 catch((error) => { 34 // error can be caused by wrong parameters or lack of internet connection 35 alert alert('error!', error message); 36 return false; 37 }); 38 }; 39	 40 return ( 41 \<view style={styles login wrapper}> 42 \<view style={styles form}> 43 \<textinput 44 style={styles form input} 45 value={username} 46 placeholder={'username'} 47 onchangetext={(text) => setusername(text)} 48 autocapitalize={'none'} 49 keyboardtype={'email address'} 50 /> 51 \<textinput 52 style={styles form input} 53 value={password} 54 placeholder={'password'} 55 securetextentry 56 onchangetext={(text) => setpassword(text)} 57 /> 58 \<touchableopacity onpress={() => douserlogin()}> 59 \<view style={styles button}> 60 \<text style={styles button label}>{'sign in'}\</text> 61 \</view> 62 \</touchableopacity> 63 \</view> 64 \<view style={styles login social}> 65 \<view style={styles login social separator}> 66 \<view style={styles login social separator line} /> 67 \<text style={styles login social separator text}>{'or'}\</text> 68 \<view style={styles login social separator line} /> 69 \</view> 70 \<view style={styles login social buttons}> 71 \<touchableopacity> 72 \<view 73 style={\[ 74 styles login social button, 75 styles login social facebook, 76 ]}> 77 \<image 78 style={styles login social icon} 79 source={require(' /assets/icon facebook png')} 80 /> 81 \</view> 82 \</touchableopacity> 83 \<touchableopacity> 84 \<view style={styles login social button}> 85 \<image 86 style={styles login social icon} 87 source={require(' /assets/icon google png')} 88 /> 89 \</view> 90 \</touchableopacity> 91 \<touchableopacity> 92 \<view style={styles login social button}> 93 \<image 94 style={styles login social icon} 95 source={require(' /assets/icon apple png')} 96 /> 97 \</view> 98 \</touchableopacity> 99 \</view> 100 \</view> 101 \</view> 102 ); 103 }; userlogin tsx 1 import react, {fc, reactelement, usestate} from 'react'; 2 import { 3 alert, 4 image, 5 text, 6 textinput, 7 touchableopacity, 8 view, 9 } from 'react native'; 10 import parse from 'parse/react native'; 11 import styles from ' /styles'; 12	 13 export const userlogin fc<{}> = ({}) reactelement => { 14 const \[username, setusername] = usestate(''); 15 const \[password, setpassword] = usestate(''); 16	 17 const douserlogin = async function () promise\<boolean> { 18 // note that these values come from state variables that we've declared before 19 const usernamevalue string = username; 20 const passwordvalue string = password; 21 return await parse user login(usernamevalue, passwordvalue) 22 then(async (loggedinuser parse user) => { 23 // login returns the corresponding parseuser object 24 alert alert( 25 'success!', 26 `user ${loggedinuser get('username')} has successfully signed in!`, 27 ); 28 // to verify that this is in fact the current user, currentasync can be used 29 const currentuser parse user = await parse user currentasync(); 30 console log(loggedinuser === currentuser); 31 return true; 32 }) 33 catch((error object) => { 34 // error can be caused by wrong parameters or lack of internet connection 35 alert alert('error!', error message); 36 return false; 37 }); 38 }; 39	 40 return ( 41 \<view style={styles login wrapper}> 42 \<view style={styles form}> 43 \<textinput 44 style={styles form input} 45 value={username} 46 placeholder={'username'} 47 onchangetext={(text) => setusername(text)} 48 autocapitalize={'none'} 49 keyboardtype={'email address'} 50 /> 51 \<textinput 52 style={styles form input} 53 value={password} 54 placeholder={'password'} 55 securetextentry 56 onchangetext={(text) => setpassword(text)} 57 /> 58 \<touchableopacity onpress={() => douserlogin()}> 59 \<view style={styles button}> 60 \<text style={styles button label}>{'sign in'}\</text> 61 \</view> 62 \</touchableopacity> 63 \</view> 64 \<view style={styles login social}> 65 \<view style={styles login social separator}> 66 \<view style={styles login social separator line} /> 67 \<text style={styles login social separator text}>{'or'}\</text> 68 \<view style={styles login social separator line} /> 69 \</view> 70 \<view style={styles login social buttons}> 71 \<touchableopacity> 72 \<view 73 style={\[ 74 styles login social button, 75 styles login social facebook, 76 ]}> 77 \<image 78 style={styles login social icon} 79 source={require(' /assets/icon facebook png')} 80 /> 81 \</view> 82 \</touchableopacity> 83 \<touchableopacity> 84 \<view style={styles login social button}> 85 \<image 86 style={styles login social icon} 87 source={require(' /assets/icon google png')} 88 /> 89 \</view> 90 \</touchableopacity> 91 \<touchableopacity> 92 \<view style={styles login social button}> 93 \<image 94 style={styles login social icon} 95 source={require(' /assets/icon apple png')} 96 /> 97 \</view> 98 \</touchableopacity> 99 \</view> 100 \</view> 101 \</view> 102 ); 103 }; 4 создание экрана входа теперь давайте создадим новый экран для вашего приложения, который будет использовать ваш userlogin userlogin компонент добавьте новый экран в качестве первого (или верхнего) экрана вашего stacknavigator stacknavigator также app tsx/app js 1 // 2	 3 // add this new screen function below the userregistrationscreen 4 function userloginscreen() { 5 return ( 6 <> 7 \<statusbar /> 8 \<safeareaview style={styles login container}> 9 \<view style={styles login header}> 10 \<image 11 style={styles login header logo} 12 source={require(' /assets/logo back4app png')} 13 /> 14 \<text style={styles login header text}> 15 \<text style={styles login header text bold}> 16 {'react native on back4app '} 17 \</text> 18 {' user login'} 19 \</text> 20 \</view> 21 \<userlogin /> 22 \</safeareaview> 23 \</> 24 ); 25 } 26	 27 // 28	 29 // add the screen as the top one at your stacknavigator 30 const app = () => { 31 return ( 32 \<navigationcontainer> 33 \<stack navigator> 34 \<stack screen name="login" component={userloginscreen} /> 35 \<stack screen name="sign up" component={userregistrationscreen} /> 36 \</stack navigator> 37 \</navigationcontainer> 38 ); 39 }; 40	 41 // продолжайте и протестируйте свой экран и компонент обратите внимание, что ваше приложение теперь будет показывать экран входа пользователя вместо экрана регистрации пользователя, из за их размещения в stacknavigator stacknavigator в списке экранов вы увидите сообщение вроде этого после входа 5 создание главного экрана и обработка навигации после входа в систему вы, как правило, захотите перенаправить пользователя на главный экран вашего приложения создайте этот экран в основном файле вашего приложения app tsx/app js 1 // 2	 3 // add this new screen function below the userregistrationscreen 4 function userloginscreen() { 5 return ( 6 <> 7 \<statusbar /> 8 \<safeareaview style={styles login container}> 9 \<view style={styles login header}> 10 \<image 11 style={styles login header logo} 12 source={require(' /assets/logo back4app png')} 13 /> 14 \<text style={styles login header text}> 15 \<text style={styles login header text bold}> 16 {'react native on back4app '} 17 \</text> 18 {' user login'} 19 \</text> 20 \</view> 21 \<userlogin /> 22 \</safeareaview> 23 \</> 24 ); 25 } 26	 27 // 28	 29 // add the screen as the top one at your stacknavigator 30 const app = () => { 31 return ( 32 \<navigationcontainer> 33 \<stack navigator> 34 \<stack screen name="login" component={userloginscreen} /> 35 \<stack screen name="sign up" component={userregistrationscreen} /> 36 \</stack navigator> 37 \</navigationcontainer> 38 ); 39 }; 40	 41 // теперь вам нужно использовать ‘react navigation’, чтобы перемещать пользователя после его входа, добавив этот новый код внутри userlogin userlogin компонента userlogin js 1 // 2 // add this import 3 import {usenavigation} from '@react navigation/native'; 4	 5 export const userlogin = () => { 6 // add this to use usenavigation hook 7 const navigation = usenavigation(); 8 9 // 10	 11 const douserlogin = async function () { 12 const usernamevalue = username; 13 const passwordvalue = password; 14 return await parse user login(usernamevalue, passwordvalue) 15 then(async (loggedinuser) => { 16 alert alert( 17 'success!', 18 `user ${loggedinuser get('username')} has successfully signed in!`, 19 ); 20 const currentuser = await parse user currentasync(); 21 console log(loggedinuser === currentuser); 22 // add this to navigate your home screen; navigation navigate takes 23 // the user to the screen named after the one passed as parameter 24 navigation navigate('home'); 25 return true; 26 }) 27 catch((error) => { 28 alert alert('error!', error message); 29 return false; 30 }); 31 }; 32 // userlogin tsx 1 // 2 // add this import 3 import {usenavigation} from '@react navigation/native'; 4	 5 export const userlogin fc<{}> = ({}) reactelement => { 6 // add this to use usenavigation hook 7 const navigation = usenavigation(); 8	 9 // 10 11 const douserlogin = async function () promise\<boolean> { 12 const usernamevalue string = username; 13 const passwordvalue string = password; 14 return await parse user login(usernamevalue, passwordvalue) 15 then(async (loggedinuser parse user) => { 16 alert alert( 17 'success!', 18 `user ${loggedinuser get('username')} has successfully signed in!`, 19 ); 20 const currentuser parse user = await parse user currentasync(); 21 console log(loggedinuser === currentuser); 22 // add this to navigate your home screen; navigation navigate takes 23 // the user to the screen named after the one passed as parameter 24 navigation navigate('home'); 25 return true; 26 }) 27 catch((error object) => { 28 alert alert('error!', error message); 29 return false; 30 }); 31 }; 32	 33 // вы будете перенаправлены на ваш новый homescreen homescreen после входа в систему вы можете улучшить этот экран, добавив этот hellouser hellouser компонент, который показывает имя текущего пользователя hellouser js 1 import react, {fc, reactelement, useeffect, usestate} from 'react'; 2 import {text} from 'react native'; 3 import parse from 'parse/react native'; 4 import styles from ' /styles'; 5	 6 export const hellouser = () => { 7 // state variable that will hold username value 8 const \[username, setusername] = usestate(''); 9	 10 // useeffect is called after the component is initially rendered and 11 // after every other render 12 useeffect(() => { 13 // since the async method parse user currentasync is needed to 14 // retrieve the current user data, you need to declare an async 15 // function here and call it afterwards 16 async function getcurrentuser() { 17 // this condition ensures that username is updated only if needed 18 if (username === '') { 19 const currentuser = await parse user currentasync(); 20 if (currentuser !== null) { 21 setusername(currentuser getusername()); 22 } 23 } 24 } 25 getcurrentuser(); 26 }, \[username]); 27	 28 // note the condition operator here, so the "hello" text is only 29 // rendered if there is an username value 30 return ( 31 \<view style={styles login wrapper}> 32 \<view style={styles form}> 33 {username !== '' && \<text>{`hello ${username}!`}\</text>} 34 \</view> 35 \</view> 36 ); 37 }; hellouser tsx 1 import react, {fc, reactelement, useeffect, usestate} from 'react'; 2 import {text} from 'react native'; 3 import parse from 'parse/react native'; 4 import styles from ' /styles'; 5	 6 export const hellouser fc<{}> = ({}) reactelement => { 7 // state variable that will hold username value 8 const \[username, setusername] = usestate(''); 9	 10 // useeffect is called after the component is initially rendered and 11 // after every other render 12 useeffect(() => { 13 // since the async method parse user currentasync is needed to 14 // retrieve the current user data, you need to declare an async 15 // function here and call it afterwards 16 async function getcurrentuser() { 17 // this condition ensures that username is updated only if needed 18 if (username === '') { 19 const currentuser = await parse user currentasync(); 20 if (currentuser !== null) { 21 setusername(currentuser getusername()); 22 } 23 } 24 } 25 getcurrentuser(); 26 }, \[username]); 27	 28 // note the condition operator here, so the "hello" text is only 29 // rendered if there is an username value 30 return ( 31 \<view style={styles login wrapper}> 32 \<view style={styles form}> 33 {username !== '' && \<text>{`hello ${username}!`}\</text>} 34 \</view> 35 \</view> 36 ); 37 }; примечание вы можете лучше ознакомиться с хуками useeffect useeffect react здесь https //reactjs org/docs/hooks effect html после вызова этого компонента внутри вашего homescreen, ваше приложение должно выглядеть так 6 создание компонента выхода из системы компонент userlogout userlogout проще, чем вход в систему, так как метод parse user logout parse user logout не принимает аргументов и автоматически очищает данные currentuser currentuser хранящиеся локально создайте этот компонент в корневом каталоге вашего приложения userlogout js 1 import react, {fc, reactelement} from 'react'; 2 import {alert, text, touchableopacity, view} from 'react native'; 3 import parse from 'parse/react native'; 4 import {usenavigation} from '@react navigation/native'; 5 import {stackactions} from '@react navigation/native'; 6 import styles from ' /styles'; 7	 8 export const userlogout = () => { 9 const navigation = usenavigation(); 10	 11 const douserlogout = async function () { 12 return await parse user logout() 13 then(async () => { 14 // to verify that current user is now empty, currentasync can be used 15 const currentuser = await parse user currentasync(); 16 if (currentuser === null) { 17 alert alert('success!', 'no user is logged in anymore!'); 18 } 19 // navigation dispatch calls a navigation action, and poptotop will take 20 // the user back to the very first screen of the stack 21 navigation dispatch(stackactions poptotop()); 22 return true; 23 }) 24 catch((error) => { 25 alert alert('error!', error message); 26 return false; 27 }); 28 }; 29	 30 return ( 31 \<view style={styles login wrapper}> 32 \<view style={styles form}> 33 \<touchableopacity onpress={() => douserlogout()}> 34 \<view style={styles button}> 35 \<text style={styles button label}>{'logout'}\</text> 36 \</view> 37 \</touchableopacity> 38 \</view> 39 \</view> 40 ); 41 }; userlogout tsx 1 import react, {fc, reactelement} from 'react'; 2 import {alert, text, touchableopacity, view} from 'react native'; 3 import parse from 'parse/react native'; 4 import {usenavigation} from '@react navigation/native'; 5 import {stackactions} from '@react navigation/native'; 6 import styles from ' /styles'; 7	 8 export const userlogout fc<{}> = ({}) reactelement => { 9 const navigation = usenavigation(); 10	 11 const douserlogout = async function () promise\<boolean> { 12 return await parse user logout() 13 then(async () => { 14 // to verify that current user is now empty, currentasync can be used 15 const currentuser parse user = await parse user currentasync(); 16 if (currentuser === null) { 17 alert alert('success!', 'no user is logged in anymore!'); 18 } 19 // navigation dispatch calls a navigation action, and poptotop will take 20 // the user back to the very first screen of the stack 21 navigation dispatch(stackactions poptotop()); 22 return true; 23 }) 24 catch((error object) => { 25 alert alert('error!', error message); 26 return false; 27 }); 28 }; 29	 30 return ( 31 \<view style={styles login wrapper}> 32 \<view style={styles form}> 33 \<touchableopacity onpress={() => douserlogout()}> 34 \<view style={styles button}> 35 \<text style={styles button label}>{'logout'}\</text> 36 \</view> 37 \</touchableopacity> 38 \</view> 39 \</view> 40 ); 41 }; добавьте этот новый компонент к homescreen homescreen чтобы вы могли протестировать его после входа в систему теперь главный экран вашего приложения будет выглядеть так если вы выполните успешный выход, вы увидите сообщение вроде этого, пока вас перенаправляют на экран userlogin userlogin , который является первым в навигационном стеке подключите вашу userregistration userregistration к кнопке регистрации внутри экрана userlogin userlogin и повторите тот же шаблон перенаправления к вашему приложению homescreen homescreen не забудьте ознакомиться с документацией react navigation react navigation для того, чтобы узнать о нескольких вариантах настройки и контролировать каждый аспект навигации вашего приложения userlogin js 1 // 2	 3 export const userlogin = () => { 4 const navigation = usenavigation(); 5	 6 const \[username, setusername] = usestate(''); 7 const \[password, setpassword] = usestate(''); 8	 9 const douserlogin = async function () { 10 // note that these values come from state variables that we've declared before 11 const usernamevalue = username; 12 const passwordvalue = password; 13 return await parse user login(usernamevalue, passwordvalue) 14 then(async (loggedinuser) => { 15 // login returns the corresponding parseuser object 16 alert alert( 17 'success!', 18 `user ${loggedinuser get('username')} has successfully signed in!`, 19 ); 20 // to verify that this is in fact the current user, currentasync can be used 21 const currentuser parse user = await parse user currentasync(); 22 console log(loggedinuser === currentuser); 23 // navigation navigate takes the user to the screen named after the one 24 // passed as parameter 25 navigation navigate('home'); 26 return true; 27 }) 28 catch((error) => { 29 // error can be caused by wrong parameters or lack of internet connection 30 alert alert('error!', error message); 31 return false; 32 }); 33 }; 34	 35 return ( 36 \<view style={styles login wrapper}> 37 \<view style={styles form}> 38 \<textinput 39 style={styles form input} 40 value={username} 41 placeholder={'username'} 42 onchangetext={(text) => setusername(text)} 43 autocapitalize={'none'} 44 keyboardtype={'email address'} 45 /> 46 \<textinput 47 style={styles form input} 48 value={password} 49 placeholder={'password'} 50 securetextentry 51 onchangetext={(text) => setpassword(text)} 52 /> 53 \<touchableopacity onpress={() => douserlogin()}> 54 \<view style={styles button}> 55 \<text style={styles button label}>{'sign in'}\</text> 56 \</view> 57 \</touchableopacity> 58 \</view> 59 \<view style={styles login social}> 60 \<view style={styles login social separator}> 61 \<view style={styles login social separator line} /> 62 \<text style={styles login social separator text}>{'or'}\</text> 63 \<view style={styles login social separator line} /> 64 \</view> 65 \<view style={styles login social buttons}> 66 \<touchableopacity> 67 \<view 68 style={\[ 69 styles login social button, 70 styles login social facebook, 71 ]}> 72 \<image 73 style={styles login social icon} 74 source={require(' /assets/icon facebook png')} 75 /> 76 \</view> 77 \</touchableopacity> 78 \<touchableopacity> 79 \<view style={styles login social button}> 80 \<image 81 style={styles login social icon} 82 source={require(' /assets/icon google png')} 83 /> 84 \</view> 85 \</touchableopacity> 86 \<touchableopacity> 87 \<view style={styles login social button}> 88 \<image 89 style={styles login social icon} 90 source={require(' /assets/icon apple png')} 91 /> 92 \</view> 93 \</touchableopacity> 94 \</view> 95 \</view> 96 <> 97 \<touchableopacity onpress={() => navigation navigate('sign up')}> 98 \<text style={styles login footer text}> 99 {"don't have an account? "} 100 \<text style={styles login footer link}>{'sign up'}\</text> 101 \</text> 102 \</touchableopacity> 103 \</> 104 \</view> 105 ); 106 }; 107	 108 // userlogin tsx 1 // 2	 3 export const userlogin fc<{}> = ({}) reactelement => { 4 const navigation = usenavigation(); 5	 6 const \[username, setusername] = usestate(''); 7 const \[password, setpassword] = usestate(''); 8	 9 const douserlogin = async function () promise\<boolean> { 10 // note that these values come from state variables that we've declared before 11 const usernamevalue string = username; 12 const passwordvalue string = password; 13 return await parse user login(usernamevalue, passwordvalue) 14 then(async (loggedinuser parse user) => { 15 // login returns the corresponding parseuser object 16 alert alert( 17 'success!', 18 `user ${loggedinuser get('username')} has successfully signed in!`, 19 ); 20 // to verify that this is in fact the current user, currentasync can be used 21 const currentuser parse user = await parse user currentasync(); 22 console log(loggedinuser === currentuser); 23 // navigation navigate takes the user to the screen named after the one 24 // passed as parameter 25 navigation navigate('home'); 26 return true; 27 }) 28 catch((error object) => { 29 // error can be caused by wrong parameters or lack of internet connection 30 alert alert('error!', error message); 31 return false; 32 }); 33 }; 34	 35 return ( 36 \<view style={styles login wrapper}> 37 \<view style={styles form}> 38 \<textinput 39 style={styles form input} 40 value={username} 41 placeholder={'username'} 42 onchangetext={(text) => setusername(text)} 43 autocapitalize={'none'} 44 keyboardtype={'email address'} 45 /> 46 \<textinput 47 style={styles form input} 48 value={password} 49 placeholder={'password'} 50 securetextentry 51 onchangetext={(text) => setpassword(text)} 52 /> 53 \<touchableopacity onpress={() => douserlogin()}> 54 \<view style={styles button}> 55 \<text style={styles button label}>{'sign in'}\</text> 56 \</view> 57 \</touchableopacity> 58 \</view> 59 \<view style={styles login social}> 60 \<view style={styles login social separator}> 61 \<view style={styles login social separator line} /> 62 \<text style={styles login social separator text}>{'or'}\</text> 63 \<view style={styles login social separator line} /> 64 \</view> 65 \<view style={styles login social buttons}> 66 \<touchableopacity> 67 \<view 68 style={\[ 69 styles login social button, 70 styles login social facebook, 71 ]}> 72 \<image 73 style={styles login social icon} 74 source={require(' /assets/icon facebook png')} 75 /> 76 \</view> 77 \</touchableopacity> 78 \<touchableopacity> 79 \<view style={styles login social button}> 80 \<image 81 style={styles login social icon} 82 source={require(' /assets/icon google png')} 83 /> 84 \</view> 85 \</touchableopacity> 86 \<touchableopacity> 87 \<view style={styles login social button}> 88 \<image 89 style={styles login social icon} 90 source={require(' /assets/icon apple png')} 91 /> 92 \</view> 93 \</touchableopacity> 94 \</view> 95 \</view> 96 <> 97 \<touchableopacity onpress={() => navigation navigate('sign up')}> 98 \<text style={styles login footer text}> 99 {"don't have an account? "} 100 \<text style={styles login footer link}>{'sign up'}\</text> 101 \</text> 102 \</touchableopacity> 103 \</> 104 \</view> 105 ); 106 }; 107	 108 // userregistration js 1 export const userregistration = () => { 2 const navigation = usenavigation(); 3	 4 const \[username, setusername] = usestate(''); 5 const \[password, setpassword] = usestate(''); 6	 7 const dousersignup = async function () { 8 // note that these values come from state variables that we've declared before 9 const usernamevalue = username; 10 const passwordvalue = password; 11 // since the signup method returns a promise, we need to call it using await 12 return await parse user signup(usernamevalue, passwordvalue) 13 then((createduser) => { 14 // parse user signup returns the already created parseuser object if successful 15 alert alert( 16 'success!', 17 `user ${createduser get('username')} was successfully created!`, 18 ); 19 // navigation navigate takes the user to the screen named after the one 20 // passed as parameter 21 navigation navigate('home'); 22 return true; 23 }) 24 catch((error) => { 25 // signup can fail if any parameter is blank or failed an uniqueness check on the server 26 alert alert('error!', error message); 27 return false; 28 }); 29 }; 30	 31 return ( 32 \<view style={styles login wrapper}> 33 \<view style={styles form}> 34 \<textinput 35 style={styles form input} 36 value={username} 37 placeholder={'username'} 38 onchangetext={(text) => setusername(text)} 39 autocapitalize={'none'} 40 keyboardtype={'email address'} 41 /> 42 \<textinput 43 style={styles form input} 44 value={password} 45 placeholder={'password'} 46 securetextentry 47 onchangetext={(text) => setpassword(text)} 48 /> 49 \<touchableopacity onpress={() => dousersignup()}> 50 \<view style={styles button}> 51 \<text style={styles button label}>{'sign up'}\</text> 52 \</view> 53 \</touchableopacity> 54 \</view> 55 \<view style={styles login social}> 56 \<view style={styles login social separator}> 57 \<view style={styles login social separator line} /> 58 \<text style={styles login social separator text}>{'or'}\</text> 59 \<view style={styles login social separator line} /> 60 \</view> 61 \<view style={styles login social buttons}> 62 \<touchableopacity> 63 \<view 64 style={\[ 65 styles login social button, 66 styles login social facebook, 67 ]}> 68 \<image 69 style={styles login social icon} 70 source={require(' /assets/icon facebook png')} 71 /> 72 \</view> 73 \</touchableopacity> 74 \<touchableopacity> 75 \<view style={styles login social button}> 76 \<image 77 style={styles login social icon} 78 source={require(' /assets/icon google png')} 79 /> 80 \</view> 81 \</touchableopacity> 82 \<touchableopacity> 83 \<view style={styles login social button}> 84 \<image 85 style={styles login social icon} 86 source={require(' /assets/icon apple png')} 87 /> 88 \</view> 89 \</touchableopacity> 90 \</view> 91 \</view> 92 <> 93 \<touchableopacity onpress={() => navigation navigate('login')}> 94 \<text style={styles login footer text}> 95 {'already have an account? '} 96 \<text style={styles login footer link}>{'log in'}\</text> 97 \</text> 98 \</touchableopacity> 99 \</> 100 \</view> 101 ); 102 }; 103	 104 // userregistration tsx 1 // 2	 3 export const userregistration fc<{}> = ({}) reactelement => { 4 const navigation = usenavigation(); 5	 6 const \[username, setusername] = usestate(''); 7 const \[password, setpassword] = usestate(''); 8	 9 const dousersignup = async function () promise\<boolean> { 10 // note that these values come from state variables that we've declared before 11 const usernamevalue string = username; 12 const passwordvalue string = password; 13 // since the signup method returns a promise, we need to call it using await 14 return await parse user signup(usernamevalue, passwordvalue) 15 then((createduser parse user) => { 16 // parse user signup returns the already created parseuser object if successful 17 alert alert( 18 'success!', 19 `user ${createduser get('username')} was successfully created!`, 20 ); 21 // navigation navigate takes the user to the screen named after the one 22 // passed as parameter 23 navigation navigate('home'); 24 return true; 25 }) 26 catch((error object) => { 27 // signup can fail if any parameter is blank or failed an uniqueness check on the server 28 alert alert('error!', error message); 29 return false; 30 }); 31 }; 32	 33 return ( 34 \<view style={styles login wrapper}> 35 \<view style={styles form}> 36 \<textinput 37 style={styles form input} 38 value={username} 39 placeholder={'username'} 40 onchangetext={(text) => setusername(text)} 41 autocapitalize={'none'} 42 keyboardtype={'email address'} 43 /> 44 \<textinput 45 style={styles form input} 46 value={password} 47 placeholder={'password'} 48 securetextentry 49 onchangetext={(text) => setpassword(text)} 50 /> 51 \<touchableopacity onpress={() => dousersignup()}> 52 \<view style={styles button}> 53 \<text style={styles button label}>{'sign up'}\</text> 54 \</view> 55 \</touchableopacity> 56 \</view> 57 \<view style={styles login social}> 58 \<view style={styles login social separator}> 59 \<view style={styles login social separator line} /> 60 \<text style={styles login social separator text}>{'or'}\</text> 61 \<view style={styles login social separator line} /> 62 \</view> 63 \<view style={styles login social buttons}> 64 \<touchableopacity> 65 \<view 66 style={\[ 67 styles login social button, 68 styles login social facebook, 69 ]}> 70 \<image 71 style={styles login social icon} 72 source={require(' /assets/icon facebook png')} 73 /> 74 \</view> 75 \</touchableopacity> 76 \<touchableopacity> 77 \<view style={styles login social button}> 78 \<image 79 style={styles login social icon} 80 source={require(' /assets/icon google png')} 81 /> 82 \</view> 83 \</touchableopacity> 84 \<touchableopacity> 85 \<view style={styles login social button}> 86 \<image 87 style={styles login social icon} 88 source={require(' /assets/icon apple png')} 89 /> 90 \</view> 91 \</touchableopacity> 92 \</view> 93 \</view> 94 <> 95 \<touchableopacity onpress={() => navigation navigate('login')}> 96 \<text style={styles login footer text}> 97 {'already have an account? '} 98 \<text style={styles login footer link}>{'log in'}\</text> 99 \</text> 100 \</touchableopacity> 101 \</> 102 \</view> 103 ); 104 }; 105	 106 // ваши экраны входа и регистрации теперь должны выглядеть так заключение в конце этого руководства вы узнали, как входить и выходить из системы пользователей parse на react native и как перемещать пользователей по вашему приложению с помощью react navigation react navigation в следующем руководстве мы покажем вам, как выполнять полезные запросы пользователей