我正在制作一个React应用程序,我制作了一个Navbar,并且它在所有组件中呈现,我只希望它一个可见,我制作了HOC功能正确。
高阶组件
这是我的导航组件
import React from 'react';
import {NavLink} from "react-router-dom";
const Navigation = () => {
return (
<div id = "navlinks">
<NavLink to = "">PROMOS</NavLink>
<NavLink to = "" >Nueva Orden</NavLink>
<NavLink to = "" >Ordenes</NavLink>
<NavLink to = "">Menú</NavLink>
<NavLink id = "logout" to = "/" >Cerrar Sesión</NavLink>
</div>
)
}
export default Navigation;
这是我的路由器
import React, { Component } from 'react';
import { BrowserRouter , Route} from "react-router-dom";
import './App.css';
import Home from "./components/Home";
import Menu from "./components/Menu";
import Navigation from "./components/Navigation";
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Navigation/>
<div>
<Route path= "/" component = {Home} exact />
<Route path= "/Menu" component = {Menu}/>
</div>
</div>
</BrowserRouter>
);
}
}
export default App;
和我的事件组件
import React, { Component } from 'react';
const LoaderHOC = (WrappedComponent) => {
return class LoaderHOC extends Component{
render(){
this.props.Navigation.length === 0 ? <div className = 'Loader'></div> : <WrapperComponent {... this.props}/>
}
}
}
export default LoaderHOC;
我想您有办法确定用户是否是loggedin。假设,您将信息存储在Isloggedin变量中,如果未登录用户,则可以使用以下内容来隐藏导航,
{ isLoggedIn && <Navigation /> }
但是,一旦您的应用程序增长,我建议您根据公共/私人状态进行不同的路线。
- 创建一个私有路线文件
import React, { Component } from 'react';
import { Redirect, Route } from 'react-router-dom';
import Navigation from "./components/Navigation";
class PrivateRoute extends Component {
render() {
// use your own logic here
const isLoggedIn = !!localStorage.getItem('token');
if (!isLoggedIn) {
return <Redirect to='/' />;
}
return (
<div>
<Navigation />
// your private route
</div>
}
}
export default PrivateRoute;
- 创建您的PublicRoute.js文件
import React, { Component } from 'react';
import { Redirect, Route } from 'react-router-dom';
class PublicRoute extends Component {
render() {
<div>
// your all public route
</div>
}
}
export default PublicRoute;
- 现在只将其包含在您的主文件中
import React, { Component } from 'react';
import { BrowserRouter , Route} from "react-router-dom";
import { PublicRoute, PrivateRoute } from './routes';
import './App.css';
import Home from "./components/Home";
import Menu from "./components/Menu";
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<PublicRoute />
<PrivateRoute />
</div>
</BrowserRouter>
);
}
}
export default App;
不要为此使用HOC
。
您必须在用户为loggedIn
的某个地方存储,如果不是,我建议您使用localStorage
,例如
localStorage.setItem("loggedIn", true);
注意:要设置localStorage
您不需要任何额外的配置。
在路由器中,您可以使用它隐藏您的component
,
{localStorage.getItem("loggedIn") && <Navigation/>}