Регистрация Parse пользователя в React Native с использованием SDK
11 мин
регистрация пользователя для react native введение в основе многих приложений лежат учетные записи пользователей, которые позволяют пользователям безопасно получать доступ к своей информации parse предоставляет специализированный класс пользователя, называемый parse user, который автоматически обрабатывает большую часть функциональности, необходимой для управления учетными записями пользователей в этом руководстве вы узнаете, как \<font color="#2166ae">parse user\</font> класс работает, создавая функцию регистрации пользователя для вашего приложения react native с использованием parse js sdk предварительные требования чтобы завершить этот учебник, вам потребуется приложение react native, созданное и подключенное к back4app https //www back4app com/docs/react native/parse sdk/react native sdk цель создать функцию регистрации пользователя с использованием parse для приложения react native 1 понимание метода signup parse user management использует \<font color="#2166ae">parse user\</font> тип объекта, который расширяет стандартный \<font color="#2166ae">parseobject\</font> тип, содержащий уникальные вспомогательные методы, такие как \<font color="#2166ae">current\</font> и \<font color="#2166ae">getusername\</font> , которые помогут вам извлекать данные пользователя в вашем приложении вы можете прочитать больше о \<font color="#2166ae">parse user\</font> объекте здесь в официальной документации https //parseplatform org/parse sdk js/api/2 18 0/parse user html в этом руководстве вы узнаете, как использовать \<font color="#2166ae">signup\</font> метод, который создает новый действительный и уникальный \<font color="#2166ae">parse user\</font> объект как локально, так и на сервере, принимая в качестве аргументов действительные \<font color="#2166ae">username\</font> и \<font color="#2166ae">password\</font> значения 2 создание компонента регистрации пользователя теперь давайте создадим функциональный компонент, который будет вызывать метод \<font color="#2166ae">signup\</font> , в нашем приложении сначала создайте новый файл в корневом каталоге с именем \<font color="#2166ae">userregistration js\</font> ( \<font color="#2166ae">userregistration tsx\</font> , если вы используете typescript) и также добавьте необходимые элементы ввода ( \<font color="#2166ae">username\</font> и \<font color="#2166ae"> password\</font> , используя хуки состояния через \<font color="#2166ae">usestate\</font> , чтобы управлять их данными userregistration js 1 import react, { fc, reactelement, usestate } from "react"; 2 import { button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration = () => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 return ( 10 <> 11 \<textinput 12 style={styles input} 13 value={username} 14 placeholder={"username"} 15 onchangetext={(text) => setusername(text)} 16 autocapitalize={"none"} 17 /> 18 \<textinput 19 style={styles input} 20 value={password} 21 placeholder={"password"} 22 securetextentry 23 onchangetext={(text) => setpassword(text)} 24 /> 25 \<button title={"sign up"} onpress={() => {}} /> 26 \</> 27 ); 28 }; 29	 30 const styles = stylesheet create({ 31 input { 32 height 40, 33 marginbottom 10, 34 backgroundcolor '#fff', 35 }, 36 }); userregistration tsx 1 import react, { fc, reactelement, usestate } from "react"; 2 import { button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration fc<{}> = ({}) reactelement => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 return ( 10 <> 11 \<textinput 12 style={styles input} 13 value={username} 14 placeholder={"username"} 15 onchangetext={(text) => setusername(text)} 16 autocapitalize={"none"} 17 /> 18 \<textinput 19 style={styles input} 20 value={password} 21 placeholder={"password"} 22 securetextentry 23 onchangetext={(text) => setpassword(text)} 24 /> 25 \<button title={"sign up"} onpress={() => {}} /> 26 \</> 27 ); 28 }; 29	 30 const styles = stylesheet create({ 31 input { 32 height 40, 33 marginbottom 10, 34 backgroundcolor '#fff', 35 }, 36 }); 3 создайте функцию регистрации теперь вы можете создать функцию регистрации, которая будет вызывать \<font color="#2166ae">signup\</font> метод javascript 1 const douserregistration = 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 // since the signup method returns a promise, we need to call it using await 6 return await parse user signup(usernamevalue, passwordvalue) 7 then((createduser) => { 8 // parse user signup returns the already created parseuser object if successful 9 alert alert( 10 'success!', 11 `user ${createduser getusername()} was successfully created!`, 12 ); 13 return true; 14 }) 15 catch((error) => { 16 // signup can fail if any parameter is blank or failed an uniqueness check on the server 17 alert alert('error!', error message); 18 return false; 19 }); 20 };1 const douserregistration = 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 // since the signup method returns a promise, we need to call it using await 6 return await parse user signup(usernamevalue, passwordvalue) 7 then((createduser parse user) => { 8 // parse user signup returns the already created parseuser object if successful 9 alert alert( 10 'success!', 11 `user ${createduser getusername()} was successfully created!`, 12 ); 13 return true; 14 }) 15 catch((error object) => { 16 // signup can fail if any parameter is blank or failed an uniqueness check on the server 17 alert alert('error!', error message); 18 return false; 19 }); 20 }; примечание создание нового пользователя с помощью \<font color="#2166ae">signup\</font> также делает его текущим вошедшим пользователем, поэтому вашему пользователю не нужно снова входить в систему, чтобы продолжить использовать ваше приложение вставьте эту функцию внутрь \<font color="#2166ae">userregistration\</font> компонента, прямо перед вызовом \<font color="#2166ae">return\</font> для того, чтобы ее можно было вызвать и протестировать не забудьте обновить действие кнопки регистрации формы \<font color="#2166ae">onpress\</font> на \<font color="#2166ae">() =\> douserregistration()\</font> и импортировать \<font color="#2166ae">alert\</font> из \<font color="#2166ae">react native\</font> ваш компонент теперь должен выглядеть так userregistration js 1 import react, { fc, reactelement, usestate } from "react"; 2 import { alert, button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration = () => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 const douserregistration = 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 // 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) => { 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 return true; 22 }) 23 catch((error) => { 24 // signup can fail if any parameter is blank or failed an uniqueness check on the server 25 alert alert("error!", error message); 26 return false; 27 }); 28 }; 29	 30 return ( 31 <> 32 \<textinput 33 style={styles input} 34 value={username} 35 placeholder={"username"} 36 onchangetext={(text) => setusername(text)} 37 autocapitalize={"none"} 38 /> 39 \<textinput 40 style={styles input} 41 value={password} 42 placeholder={"password"} 43 securetextentry 44 onchangetext={(text) => setpassword(text)} 45 /> 46 \<button title={"sign up"} onpress={() => douserregistration()} /> 47 \</> 48 ); 49 }; 50	 51 const styles = stylesheet create({ 52 input { 53 height 40, 54 marginbottom 10, 55 backgroundcolor "#fff", 56 }, 57 }); userregistration tsx 1 import react, { fc, reactelement, usestate } from "react"; 2 import { alert, button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration fc<{}> = ({}) reactelement => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 const douserregistration = 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 return true; 22 }) 23 catch((error object) => { 24 // signup can fail if any parameter is blank or failed an uniqueness check on the server 25 alert alert("error!", error message); 26 return false; 27 }); 28 }; 29	 30 return ( 31 <> 32 \<textinput 33 style={styles input} 34 value={username} 35 placeholder={"username"} 36 onchangetext={(text) => setusername(text)} 37 autocapitalize={"none"} 38 /> 39 \<textinput 40 style={styles input} 41 value={password} 42 placeholder={"password"} 43 securetextentry 44 onchangetext={(text) => setpassword(text)} 45 /> 46 \<button title={"sign up"} onpress={() => douserregistration()} /> 47 \</> 48 ); 49 }; 50	 51 const styles = stylesheet create({ 52 input { 53 height 40, 54 marginbottom 10, 55 backgroundcolor "#fff", 56 }, 57 }); 4 тестирование компонента последний шаг — использовать наш новый компонент внутри вашего приложения react native \<font color="#2166ae">app js\</font> файл (или \<font color="#2166ae">app tsx\</font> если вы используете typescript) app js 1 import { userregistration } from " /userregistration"; 2 / 3 your functions here 4 / 5 return ( 6 <> 7 \<statusbar /> 8 \<safeareaview style={styles container}> 9 <> 10 \<text style={styles title}>react native on back4app\</text> 11 \<text>user registration tutorial\</text> 12 \<userregistration /> 13 \</> 14 \</safeareaview> 15 \</> 16 ); 17	 18 // remember to add some styles at the end of your file 19 const styles = stylesheet create({ 20 container { 21 flex 1, 22 backgroundcolor "#fff", 23 alignitems "center", 24 justifycontent "center", 25 }, 26 title { 27 fontsize 20, 28 fontweight "bold", 29 }, 30 }); app tsx 1 import { userregistration } from " /userregistration"; 2 / 3 your functions here 4 / 5 return ( 6 <> 7 \<statusbar /> 8 \<safeareaview style={styles container}> 9 <> 10 \<text style={styles title}>react native on back4app\</text> 11 \<text>user registration tutorial\</text> 12 \<userregistration /> 13 \</> 14 \</safeareaview> 15 \</> 16 ); 17	 18 // remember to add some styles at the end of your file 19 const styles = stylesheet create({ 20 container { 21 flex 1, 22 backgroundcolor "#fff", 23 alignitems "center", 24 justifycontent "center", 25 }, 26 title { 27 fontsize 20, 28 fontweight "bold", 29 }, 30 }); теперь ваше приложение должно выглядеть так после ввода желаемых учетных данных пользователя вы увидите это сообщение после нажатия на \<font color="#2166ae">зарегистрироваться\</font> если все прошло успешно обработку ошибок можно протестировать, если вы попытаетесь зарегистрировать пользователя с тем же именем пользователя, что и раньше вы получите другую ошибку, если попытаетесь зарегистрироваться без пароля заключение в конце этого руководства вы узнали, как регистрировать новых пользователей parse на react native в следующем руководстве мы покажем вам, как входить и выходить из системы