У меня есть основной компонент маршрутов, подобный этому
import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import PrivateRoute from './PrivateRoute'
import AdminPanel from './pages/AdminPanel/AdminPanel'
import SignIn from './pages/SignIn'
import '../assets/stylesheets/styles.scss'
const AppContent = props => <Router>
<div>
<PrivateRoute path='/' component={AdminPanel} />
<Route path='/sign-in' component={SignIn} />
</div>
</Router>
export default AppContent
Вот PrivateRoute.jsx
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
const PrivateRoute = ({ component: Component, currentUser, ...rest }) => (
<Route
{...rest}
render={props =>
currentUser ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/sign-in',
state: { from: props.location }
}}
/>
)
}
/>
)
export default connect(({ currentUser }) => ({ currentUser }))(PrivateRoute)
, поэтому, если currentUser
равно нулю, оно перенаправляется на /sign-in
, чтопрекрасно.Однако проблема в том, что если есть currentUser
и я перехожу к /sign-in
, я все равно получаю компонент AdminPanel
.
Вот редуктор currentUser
и компонент AdminPanel
в случае необходимости.
import { SIGNIN, SIGNOUT } from '../actions/types'
// so here the default state is null, however if I change it to `{}` which will mean there is a user then I am not able to go to the `/sign-in`
export default (state = null, action) => {
switch (action.type) {
case SIGNIN:
return action.payload
case SIGNOUT:
return null
default:
return state
}
}
И AdminPanel
import React, { Component } from 'react'
import { Route, Switch } from 'react-router-dom'
import Box, { Container } from 'react-layout-components'
import LeftMenu from '../../components/AdminPanel/LeftMenu'
import Header from '../../components/AdminPanel/Header'
import Home from './Home'
import Dashboard from './Dashboard'
import Categories from './Categories'
import Partners from './Partners'
import Users from './Users'
import TeamMembers from './TeamMembers'
import Settings from './Settings'
import Help from './Help'
class AdminPanel extends Component {
render () {
return (
<Box>
<Container minWidth={300}>
<LeftMenu />
</Container>
<Container padding='15px' width='100%'>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/dashboard' component={Dashboard} />
<Route exact path='/categories' component={Categories} />
<Route exact path='/partners' component={Partners} />
<Route exact path='/users' component={Users} />
<Route exact path='/team-members' component={TeamMembers} />
<Route exact path='/settings' component={Settings} />
<Route exact path='/help' component={Help} />
</Switch>
<Header />
</Container>
</Box>
)
}
}
export default AdminPanel
И SignIn
- это простой компонент на основе классов
import React, { Component } from 'react'
class SignIn extends Component {
render () {
return (
<div>SignIn</div>
)
}
}
export default SignIn