所以我的问题是,除非用户通过身份验证,否则我不希望登录和注册选项卡能够看到导航的其余部分。身份验证后,我想根据用户的角色向用户显示这些选项卡的子集。然而,当我尝试条件导航栏时,除非我刷新,否则渲染不会发生。我对反应开发还很陌生,因此任何简单的解决方法都将不胜感激。 我的目标是获得一个登录/注册页面,让用户根据他们的角色查看导航栏组件。提前致谢。
function App() {
return (
<BrowserRouter>
<Navbar />
<div className="container mt-2" style={{ marginTop: 40 }}>
<Switch>
<Route path= "/login">
<Login/>
</Route>
<Route path="/addStock">
<Stock />
</Route>
<Route path='/addSector'>
<Sector />
</Route>
<Route path='/manageSector'>
<ManageSector />
</Route>
<Route path="/addCompany">
<Company />
</Route>
<Route path="/uploadSheet">
<Data />
</Route>
<Route path="/manageCompanies">
<ManageCompanies />
</Route>
<Route path="/addIPO">
<IPO />
</Route>
<Route path="/manageIPO">
<ManageIPO />
</Route>
<Route path="/stockexchange">
<StockExchange />
</Route>
<Route path="/managestockexchange">
<ManageStockExchange />
</Route>
<Route path="/signup">
<SignUp />
</Route>
<Route path="/comparisonCharts">
<ComparisonCharts />
</Route>
</Switch>
</div>
</BrowserRouter>
);
}
答案 0 :(得分:0)
React 仅在任何状态更改时更新页面。在您的页面中,您可以使用 useState 钩子,或者如果您使用 redux/mobx 等...在您的应用程序中,您可以将您的用户数据写入您的商店并在页面中监听用户数据状态。第一个选项useState钩子代码是这样的
import React, { useState } from 'react';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const login = (userData) => {
const response = fetch()... //Call your api here
if(response === true)
setIsLoggedIn(response)
}
return (
<BrowserRouter>
<div className="container mt-2" style={{ marginTop: 40 }}>
<Switch><Navbar />
{isLoggedIn && <Route path= "/login">
<Login/>
</Route>}
<Route path="/addStock">
<Stock />
</Route>
<Route path='/addSector'>
<Sector />
</Route>
<Route path='/manageSector'>
<ManageSector />
</Route>
<Route path="/addCompany">
<Company />
</Route>
<Route path="/uploadSheet">
<Data />
</Route>
<Route path="/manageCompanies">
<ManageCompanies />
</Route>
<Route path="/addIPO">
<IPO />
</Route>
<Route path="/manageIPO">
<ManageIPO />
</Route>
<Route path="/stockexchange">
<StockExchange />
</Route>
<Route path="/managestockexchange">
<ManageStockExchange />
</Route>
<Route path="/signup">
<SignUp />
</Route>
<Route path="/comparisonCharts">
<ComparisonCharts />
</Route>
</Switch>
</div>
</BrowserRouter>