我正在尝试在我的React应用程序中创建一个登录系统,它应该显示不同的UI(目前是不同的导航栏(,这取决于用户是否有管理员自定义令牌、用户自定义令牌或用户未登录。
目前,管理员用户可以获得令牌,但我不知道如何根据用户的令牌来更改UI。
代码:
Header.js
import React from 'react';
import {Link} from 'react-router-dom';
import './Header.scss';
import PublicNavigation from '../PublicLinks/PublicLinks';
import AdminNavigation from '../AdminLinks/AdminLinks';
import UserNavigation from '../UserLinks/UserLinks';
import SignUpButton from '../SignUpButton/SignUpButton';
import { connect } from 'react-redux';
import LogOut from '../LogOut/LogOut'
const Header = (props) => {
// Firebase Login Check -- This is what changes the navigation based on whether the user is logged in or not!
const {auth } = props;
// console.log(auth);
const nav = auth.uid ? <UserNavigation/> : <PublicNavigation/>
const button = auth.uid ? <LogOut/> : <SignUpButton/>
return (
<div className = "Header">
<div className = "Logo">
{/* Company Logo */}
<h1 className = "CompanyName"> Logo.</h1>
</div>
{/* These are the login , signup and log out buttons */}
{ button }
<div className = "Navigation">
{ nav }
</div>
</div>
)
}
const mapStateToProps = (state) => {
return {
auth: state.firebase.auth
}
}
export default connect(mapStateToProps)(Header)
functions/index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addAdminRole = functions.https.onCall((data, context) => {
// get user and add admin custom claim
return admin.auth().getUserByEmail(data.email).then(user => {
return admin.auth().setCustomUserClaims(user.uid, {
admin: true
})
}).then(() => {
return {
message: `Success! ${data.email} has been made an admin.`
}
}).catch(err => {
return err;
});
});
您的逻辑似乎是正确的。你已经完成了大部分工作。
你所要做的就是弄清楚谁登录了。管理员还是其他人?我看到你有一个auth
对象,我想你可以理解登录的用户类型。一旦你得到了这些信息,你的代码就会正常工作。
const nav = auth.uid ? <UserNavigation/> : <PublicNavigation/>
我不确定auth
是否有userType
字段,但一定有类似的内容。
示例:
const Nav = () => {
if(auth.userType === "admin")
return <AdminNav/>
else if(auth.userType === "user")
return <UserNav/>
else
return <PublicNav/>
}
然后可以将其用作渲染函数中的<Nav/>
。
下面是一个非常基本的例子。
https://stackblitz.com/edit/react-hmjkmq?file=src/App.js