React Native
...
Users
Inicio de Sesión en React Native con Parse SDK
20 min
inicio de sesión y cierre de sesión de usuario para react native introducción después de implementar un componente que maneja el registro de usuarios en parse en la última guía, ahora aprenderás cómo iniciar y cerrar sesión de usuarios utilizando la misma parse user parse user clase también aprenderás a instalar y configurar react navigation react navigation para que puedas navegar al usuario a través de tus nuevas pantallas y componentes el parse user login parse user login método almacena en tu almacenamiento local una sesión de usuario válida, por lo que futuras llamadas a métodos como currentasync currentasync recuperarán con éxito tus datos de usuario por otro lado, logout logout eliminará esta sesión del disco y cerrará sesión de cualquier servicio vinculado en tu servidor parse en cualquier momento, puedes acceder al proyecto completo de android construido con este tutorial en nuestros repositorios de github repositorio de ejemplo en kotlin repositorio de ejemplo en java requisitos previos para completar este tutorial, necesitarás una aplicación de react native creada y conectada a back4app completa las guías anteriores para que puedas tener una mejor comprensión de la clase de usuario de parse objetivo para construir una función de inicio y cierre de sesión de usuario utilizando parse para una aplicación de react native 1 instalando dependencias en algún momento, cada aplicación en react native necesitará navegación entre pantallas ahora aprenderás cómo instalar y configurar la biblioteca más utilizada en react native para esto, react navigation react navigation ve a tu directorio raíz del proyecto e instala las siguientes dependencias si estás desarrollando para ios, necesitas instalar los pods para completar el auto vinculado de tu aplicación nota el vinculado es automático para react native 0 60+ 0 60+ para todas las plataformas, así que si aún estás utilizando una versión anterior de rn, echa un vistazo a la documentación de react native aquí https //reactnative dev/docs/linking libraries ios en el archivo de entrada de tu aplicación ( app tsx app tsx o app js app js ), agrega esta línea de importación en la parte superior del archivo ahora necesitas mover tus componentes dentro del react navigation react navigation contenedor, que encapsulará tu aplicación dentro de un 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; la biblioteca de navegación principal tiene diferentes módulos de navegación adicionales como pila, pestañas, cajón, entre otros el navegador de pila es el más sencillo y el que usarás en esta guía procede con la instalación 2 creando un stacknavigator ahora vamos a crear y configurar un stacknavigator stacknavigator este módulo gestionará y manejará la navegación entre pantallas en tu aplicación dado que no es un objetivo aquí darte una comprensión profunda de react navigation comprensión profunda de react navigation , por favor visita la documentación oficial https //reactnavigation org/docs/hello react navigation/ para saber más en tu app js app js ( app tsx app tsx si estás usando typescript) archivo, importa y crea un stacknavigator stacknavigator , crea una función que contenga tu pantalla de registro de usuario e inserta el navegador dentro de tu aplicación navigationcontainer navigationcontainer tu archivo principal debería verse así 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; si ejecutas tu aplicación ahora, notarás la inclusión de un encabezado en la parte superior de la pantalla que contiene el nombre de tu pantalla 3 creando un componente de inicio de sesión ahora construyamos el userlogin userlogin componente funcional en tu aplicación crea un nuevo archivo en tu directorio raíz llamado userlogin js userlogin js ( userlogin tsx userlogin tsx si estás usando typescript) y agrega los elementos de entrada usando hooks de estado para gestionar sus datos 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 }; ahora puedes implementar la función que llamará al parse user login parse user login método, utilizando variables de estado 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 }; inserte esta función dentro del userlogin userlogin componente, justo antes de la return return llamada, para ser llamada y probada recuerde actualizar la acción del botón de inicio de sesión del formulario onpress onpress a () => douserlogin() () => douserlogin() y para importar alert alert de react native react native su componente ahora debería verse así 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 creando una pantalla de inicio de sesión ahora vamos a crear una nueva pantalla para tu aplicación que utilizará tu userlogin userlogin componente agrega la nueva pantalla como la primera (o superior) pantalla de tu stacknavigator stacknavigator también 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 // adelante, prueba tu pantalla y componente nota que tu aplicación ahora mostrará la pantalla de inicio de sesión del usuario en lugar de la pantalla de registro del usuario, debido a su ubicación en la stacknavigator stacknavigator de la lista de pantallas verás un mensaje como este después de iniciar sesión 5 creando una pantalla de inicio y manejando la navegación después de iniciar sesión, generalmente querrás llevar al usuario a la pantalla de inicio de tu aplicación crea esta pantalla en el archivo principal de tu aplicación 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 // ahora necesitas usar ‘react navigation’ para navegar al usuario después de que inicie sesión, agregando este nuevo código dentro del userlogin userlogin componente 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 // serás redirigido a tu nuevo homescreen homescreen después de iniciar sesión puedes mejorar esta pantalla agregando este hellouser hellouser componente que muestra el nombre de usuario del usuario actual 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 }; nota puedes echar un vistazo más de cerca a los useeffect useeffect de react aquí https //reactjs org/docs/hooks effect html después de llamar a este componente dentro de tu homescreen, tu aplicación debería verse así 6 creando un componente de cierre de sesión el userlogout userlogout componente es más simple que el de inicio de sesión ya que el parse user logout parse user logout método no toma argumentos y borra automáticamente los datos de currentuser currentuser almacenados localmente crea este componente en el directorio raíz de tu aplicación 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 }; agrega este nuevo componente a homescreen homescreen para que puedas probarlo después de iniciar sesión la pantalla de inicio de tu aplicación se verá así ahora si realizas un cierre de sesión exitoso, verás un mensaje como este mientras te redirigen a la userlogin userlogin pantalla, que es la primera en la pila de navegación conecta tu userregistration userregistration a un botón de registro dentro de la userlogin userlogin pantalla y repite el mismo patrón de redirección a tu app homescreen homescreen recuerda leer la documentación de react navigation react navigation para descubrir varias opciones de personalización y controlar cada aspecto de la navegación de tu app 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 // tus pantallas de inicio de sesión y registro ahora deberían verse así conclusión al final de esta guía, aprendiste cómo iniciar y cerrar sesión de usuarios de parse en react native y cómo navegar a los usuarios a través de tu aplicación usando react navigation react navigation en la próxima guía, te mostraremos cómo realizar consultas útiles de usuarios