我对ReactJS非常陌生。我的查询是我想停留在ReactJS页面的同一组件上。下面是我的代码。
App.js
import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom'
import { authenticationService } from './_service/authentication.service'
import { PrivateRoute } from './components/Routes/PrivateRoute';
import Navbar from './components/Navbar/Navbar'
import Landing from './components/Landing/Landing'
import Login from './components/Login/Login'
import Register from './components/Register/Register'
import Home from './components/Home/Home'
import SideBar from './components/SideBar/SideBar';
class App extends Component { render(){
return (
<Router>
<div className="App">
<Navbar />
{authenticationService.currentUserValue ? <SideBar/> : null}
<Route exact path="/" component={Landing} />
<div className="container">
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/home" component={Home} />
</div>
</div>
</Router>
) } }
以上路线是登录后我项目的主要路线文件,它将我重定向到主页。在主页上,我正在加载标题,侧边栏和Content(Component)。这里的content(Component)是不同的,这取决于侧边栏链接。
Home.js
import React, { Component } from 'react'
import { BrowserRouter as Router} from 'react-router-dom'
// import Home from './components/Home/Home'
import { authenticationService } from '../../_service/authentication.service'
// import Navbar from '../Navbar/Navbar'
import Sidebar from '../SideBar/SideBar'
// import Landing from '../Landing/Landing'
import Profile from '../Profile/Profile'
import AboutUs from '../Profile/AboutUs'
class Home extends Component {
constructor(props){
super(props);
if (authenticationService.currentUserValue) {
// this.props.history.push('/home');
this.props.history.push('/home');//this.state.initialPage
}
this.state={
initialPage:<Profile/>
}
}
routeSidebar = (flag) => {
switch(flag) {
case 'AboutUs':
this.setState({
initialPage:<AboutUs/>
})
break;
default:
this.setState({
initialPage:<Profile/>
})
break;
}
}
render() {
const {initialPage} = this.state;
return (
<Router>
<div className="Home">
<Sidebar routeSidebar={this.routeSidebar} />
{initialPage}
</div>
</Router>
);
}
}
export default Home;
答案 0 :(得分:1)
您可以使用两种不同的方式来执行此操作,或者可以使用localStorage,cookie或可以使用props.location
,如下所示。
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { authenticationService } from '../../_service/authentication.service';
export const PrivateRoute = ({ component: Component, roles, ...rest }) => (
<Route {...rest} render={props => {
const currentUser = authenticationService.currentUserValue;
if (!currentUser) {
// not logged in so redirect to login page with the return url
return <Redirect to={{ pathname: '/', state: { from: props.location } }} />
}
// check if route is restricted by role
if (roles && roles.indexOf(currentUser.role) === -1) {
// role not authorised so redirect to home page
return <Redirect to={{ pathname: '/'}} />
}
// authorised so return component
return <Component {...props} />
}} />
)