简体   繁体   中英

Private Route React router always redirects to first Route

Actually I had no problem with directing to another route by clicking a button, but somehow I can't direct manually by changing the URL. Every time I was about changing the URL (ex: localhost:3000/proposal), it always directs me to the first Route . Here's the Route in order:

<Switch>
                  <Route exact path="/" component={Landing} /> // => always goin here
                  <Route exact path="/login" component={Login} />
                  <Route exact path="/register" component={Register} />

                  {/* Dashboard */}
                  <PrivateRoute
                    exact
                    path="/home"
                    component={Home}
                    StickyNav={StickyNavbar}
                  />
                  <PrivateRoute
                    exact
                    path="/proposal"
                    component={Proposal}
                    StickyNav={StickyNavbar}
                  />
                  <PrivateRoute
                    exact
                    path="/laporan"
                    component={Laporan}
                    StickyNav={StickyNavbar}
                  />

                  <Route component={NotFound} />
                </Switch>

It doesn't direct me to Landing if I change the URL to non-private route. Here's my private route code:

import React from "react"
import { Route, Redirect } from "react-router-dom"
import { connect } from "react-redux"
import PropTypes from "prop-types"

const mapStateToProps = state => ({
  auth: state.auth
})

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      auth.isAuthenticated === true ? (
        <Component {...props} {...rest} />
      ) : (
        <Redirect to="/login" />
      )
    }
  />
)

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
}

export default connect(mapStateToProps)(PrivateRoute)

Based on @zhuber said, the auth object from react-redux doesn't call before the private route was called. So I changed the condition from isAuthenticated using localStorage like this:

      !isEmpty(localStorage.jwtToken) ? (
        <Component {...props} {...rest} />
      ) : (
        <Redirect to="/login" />
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM