React Native
...
Users
Получение текущего пользователя в React Native через Parse
7 мин
получить текущего пользователя для react native введение после реализации регистрации и входа пользователя в ваше приложение, вам нужно получить данные о текущем вошедшем пользователе, чтобы выполнять различные действия и запросы поскольку react native использует asyncstorage asyncstorage в качестве локального хранилища, эти данные можно получить с помощью parse currentasync parse currentasync внутри компонента вашего приложения предварительные условия чтобы завершить этот учебник, вам потребуется приложение react native, созданное и подключенное к back4app завершите предыдущие руководства, чтобы лучше понять класс пользователя parse цель получить данные текущего пользователя, используя parse для приложения react native 1 получение текущего пользователя метод parse currentasync parse currentasync может быть использован в любом месте вашего кода, после правильной настройки вашего приложения для использования parse и asyncstorage его ответ будет объектом вашего текущего пользователя ( parse user parse user ) или null, если в данный момент нет вошедшего в систему пользователя javascript 1 const getcurrentuser = async function () { 2 const currentuser = await parse user currentasync(); 3 if (currentuser !== null) { 4 alert alert( 5 'success!', 6 `${currentuser get('username')} is the current user!`, 7 ); 8 } 9 return currentuser; 10 };1 const getcurrentuser = async function () promise\<parse user> { 2 const currentuser parse user = await parse user currentasync(); 3 if (currentuser !== null) { 4 alert alert( 5 'success!', 6 `${currentuser get('username')} is the current user!`, 7 ); 8 } 9 return currentuser; 10 }; этот метод необходим в ситуациях, когда у вас нет доступа к состоянию вашего приложения или данным пользователя, что позволяет выполнять соответствующие запросы parse в любом компоненте вашего приложения 2 использование текущего пользователя в компоненте react native в наших предыдущих руководствах, parse currentasync parse currentasync уже использовался для тестирования и внутри компонента hellouser hellouser вот снова полный компонент hellouser js 1 import react, {fc, reactelement, useeffect, usestate} from 'react'; 2 import {text, view} 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 conditional 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, view} 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 conditional 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 }; в этом случае метод parse currentasync parse currentasync получает имя пользователя и обновляет переменную состояния, которая отображается внутри jsx компонента заключение в конце этого руководства вы узнали, как получить данные текущего пользователя parse из локального хранилища в react native в следующем руководстве мы покажем вам, как позволить вашему пользователю сбросить свой пароль