在React中使用Parse获取当前用户教程指南
6 分
获取当前用户用于React
介绍
在实现用户注册和登录后,您需要检索当前登录用户的数据以执行不同的操作和请求。可以通过在您的应用组件中使用 Parse.User.current 来快速检索这些数据。
先决条件
要完成本教程,您需要:
目标
获取当前用户数据,使用Parse为React应用程序进行提取。
1 - 检索当前用户
方法 Parse.User.current 可以在您的代码中的任何地方使用,前提是您已正确配置应用以使用Parse。其响应将是您当前用户的对象 (Parse.User),如果当前没有登录用户,则为null。
1 const getCurrentUser = async function (): Promise<Parse.User | null> {
2 const currentUser: Parse.User = await Parse.User.current();
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 组件中使用当前用户
在我们之前的指南中,Parse.User.current 方法已经用于测试,显示当前用户名在用户登录指南中。这里是UserLogin 组件代码,仔细看看getCurrentUser 函数:
1 import React, { useState, FC, ReactElement } from 'react';
2 import './App.css';
3 import { Button, Divider, Input } from 'antd';
4 const Parse = require('parse/dist/parse.min.js');
5
6 export const UserLogin: FC<{}> = (): ReactElement => {
7 // State variables
8 const [username, setUsername] = useState('');
9 const [password, setPassword] = useState('');
10 const [currentUser, setCurrentUser] = useState<Parse.Object | null>(null);
11
12 const doUserLogIn = async function (): Promise<boolean> {
13 // Note that these values come from state variables that we've declared before
14 const usernameValue: string = username;
15 const passwordValue: string = password;
16 try {
17 const loggedInUser: Parse.User = await Parse.User.logIn(usernameValue, passwordValue);
18 // logIn returns the corresponding ParseUser object
19 alert(
20 `Success! User ${loggedInUser.get('username')} has successfully signed in!`,
21 );
22 // To verify that this is in fact the current user, `current` can be used
23 const currentUser: Parse.User = await Parse.User.current();
24 console.log(loggedInUser === currentUser);
25 // Clear input fields
26 setUsername('');
27 setPassword('');
28 // Update state variable holding current user
29 getCurrentUser();
30 return true;
31 } catch (error: any) {
32 // Error can be caused by wrong parameters or lack of Internet connection
33 alert(`Error! ${error.message}`);
34 return false;
35 }
36 };
37
38 const doUserLogOut = async function (): Promise<boolean> {
39 try {
40 await Parse.User.logOut();
41 // To verify that current user is now empty, currentAsync can be used
42 const currentUser: Parse.User = await Parse.User.current();
43 if (currentUser === null) {
44 alert('Success! No user is logged in anymore!');
45 }
46 // Update state variable holding current user
47 getCurrentUser();
48 return true;
49 } catch (error: any) {
50 alert(`Error! ${error.message}`);
51 return false;
52 }
53 };
54
55 // Function that will return current user and also update current username
56 const getCurrentUser = async function (): Promise<Parse.User | null> {
57 const currentUser: (Parse.User | null) = await Parse.User.current();
58 // Update state variable holding current user
59 setCurrentUser(currentUser);
60 return currentUser;
61 }
62
63 return (
64 <div>
65 <div className="header">
66 <img
67 className="header_logo"
68 alt="Back4App Logo"
69 src={
70 'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png'
71 }
72 />
73 <p className="header_text_bold">{'React on Back4App'}</p>
74 <p className="header_text">{'User Login'}</p>
75 </div>
76 {currentUser === null &&
77 (<div className="container">
78 <h2 className="heading">{'User Login'}</h2>
79 <Divider />
80 <div className="form_wrapper">
81 <Input
82 value={username}
83 onChange={(event) => setUsername(event.target.value)}
84 placeholder="Username"
85 size="large"
86 className="form_input"
87 />
88 <Input
89 value={password}
90 onChange={(event) => setPassword(event.target.value)}
91 placeholder="Password"
92 size="large"
93 type="password"
94 className="form_input"
95 />
96 </div>
97 <div className="form_buttons">
98 <Button
99 onClick={() => doUserLogIn()}
100 type="primary"
101 className="form_button"
102 color={'#208AEC'}
103 size="large"
104 >
105 Log In
106 </Button>
107 </div>
108 </div>)
109 }
110 {currentUser !== null &&
111 (<div className="container">
112 <h2 className="heading">{'User Screen'}</h2>
113 <Divider />
114 <h2 className="heading">{`Hello ${currentUser.get('username')}!`}</h2>
115 <div className="form_buttons">
116 <Button
117 onClick={() => doUserLogOut()}
118 type="primary"
119 className="form_button"
120 color={'#208AEC'}
121 size="large"
122 >
123 Log Out
124 </Button>
125 </div>
126 </div>)
127 }
128 </div>
129 );
130 };在这个组件中,Parse.User.current 方法检索用户名并更新在组件 JSX 中渲染的状态变量。 将这些类添加到你的App.css 文件中以完全渲染布局样式:
1 @import '~antd/dist/antd.css';
2
3 .App {
4 text-align: center;
5 }
6
7 html {
8 box-sizing: border-box;
9 outline: none;
10 overflow: auto;
11 }
12
13 *,
14 *:before,
15 *:after {
16 margin: 0;
17 padding: 0;
18 box-sizing: inherit;
19 }
20
21 h1,
22 h2,
23 h3,
24 h4,
25 h5,
26 h6 {
27 margin: 0;
28 font-weight: bold;
29 }
30
31 p {
32 margin: 0;
33 }
34
35 body {
36 margin: 0;
37 background-color: #fff;
38 }
39
40 .container {
41 width: 100%;
42 max-width: 900px;
43 margin: auto;
44 padding: 20px 0;
45 text-align: left;
46 }
47
48 .header {
49 align-items: center;
50 padding: 25px 0;
51 background-color: #208AEC;
52 }
53
54 .header_logo {
55 height: 55px;
56 margin-bottom: 20px;
57 object-fit: contain;
58 }
59
60 .header_text_bold {
61 margin-bottom: 3px;
62 color: rgba(255, 255, 255, 0.9);
63 font-size: 16px;
64 font-weight: bold;
65 }
66
67 .header_text {
68 color: rgba(255, 255, 255, 0.9);
69 font-size: 15px;
70 }
71
72 .heading {
73 font-size: 22px;
74 }
75
76 .flex {
77 display: flex;
78 }
79
80 .flex_between {
81 display: flex;
82 justify-content: space-between;
83 }
84
85 .flex_child {
86 flex: 0 0 45%;
87 }
88
89 .heading_button {
90 margin-left: 12px;
91 }
92
93 .list_item {
94 padding-bottom: 15px;
95 margin-bottom: 15px;
96 border-bottom: 1px solid rgba(0,0,0,0.06);
97 text-align: left;
98 }
99
100 .list_item_title {
101 color: rgba(0,0,0,0.87);
102 font-size: 17px;
103 }
104
105 .list_item_description {
106 color: rgba(0,0,0,0.5);
107 font-size: 15px;
108 }结论
在本指南的最后,你学习了如何从 React 的本地存储中检索当前的 Parse 用户数据。在下一个指南中,我们将向你展示如何让用户重置他的密码。