如何解决如果用户未登录,如何隐藏导航
Route.js
const Layout = () => {
const SecuredRoute = ({ ...props }) => (
console.log(props.path),<Route path={props.path} render={(data) => (
console.log(data),localStorage.getItem('accessToken')
? <props.render {...data} />
: <Redirect to='/login' />
)} />
)
return (
<>
<BrowserRouter>
<Navbar /> // It needs to be hidden if user is not logged in
<div className='layout'>
<Switch>
<Route exact path='/home' component={Home} />
<Route exact path='/login' component={Login} />
<SecuredRoute exact path='/about' component={About} />
<Route exact path='/contact' component={Contact} />
<Route exact path='/add' component={AddBlog} />
<Route exact path='/edit/:id' component={UpdateBlog} />
<Route exact path='/blog/:id' component={Blogdetail} />
<Route component={Home} />
</Switch>
</div>
<Footer />
</BrowserRouter>
</>
)
}
export default Layout
我想如果用户未登录,则必须隐藏导航栏。这意味着当route ='/ login'导航栏需要隐藏时。您已经尝试了很多方法,但是没有任何效果。我是React的新手。任何帮助将不胜感激?
解决方法
您可以创建一个布尔变量并将其短路。
render() {
const visible = true;
const notVisible = false;
return (
<div>
{visible && <p>I am visible</p>}
{notVisible && <p>I am not visible</p>}
</div>
);
}
,
在我的朋友Navbar
组件中尝试一下:
const [loggedIn,setLoggedIn] = useState(false);
const Layout = () => {
const SecuredRoute = ({ ...props }) => (
console.log(props.path),<Route path={props.path} render={(data) => (
console.log(data),localStorage.getItem('accessToken')
? <props.render {...data} />
: <Redirect to='/login' />
)} />
)
return (
<>
<BrowserRouter>
<Navbar loggedIn={loggedIn} /> // It needs to be hidden if user is not logged in
<div className='layout'>
<Switch>
<Route exact path='/home' component={Home} />
<Route exact path='/login' component={() => <Login setLoggedIn={setLoggedIn} />} />
<SecuredRoute exact path='/about' component={About} />
<Route exact path='/contact' component={Contact} />
<Route exact path='/add' component={AddBlog} />
<Route exact path='/edit/:id' component={UpdateBlog} />
<Route exact path='/blog/:id' component={Blogdetail} />
<Route component={Home} />
</Switch>
</div>
<Footer />
</BrowserRouter>
</>
)
}
export default Layout
我给了setState来登录组件。当用户登录loggedIn(true)
并且父状态更改时,您将提供一个布尔值。
在Navbar
组件中:
return(
loggedIn
?
//The Body of NavBar
:
""
}
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。