简体   繁体   中英

Passing parameter to Route in React Router

I have defined a route which cannot be accessed unless the user has logged in. The code for this is as follows:

    const App = ({ userLoggedIn }) => {
return (
        <Router>
          <div className="App">
            <Header userLoggedIn={ userLoggedIn }/>
            <ProtectedRoute path='/content' component={ Day } userLoggedIn={ userLoggedIn } />
            <Footer />
          </div>
        </Router>
      );
    }

I am passing the userLoggedIn as parameter as the App is keeping the state of it. I am defining ProtectedRoute in a similar way as the Auth example in React Router documentation.

const ProtectedRoute = ({ userLoggedIn, component, ...rest }) => (
  <Route {...rest} render={ props => (
    userLoggedIn ? (
      React.createElement(component, props)
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

But userLoggedIn is always null (even when the value is not null before calling the ProtectedRoute).


I have created a simpler example which I'm testing in the App. I have added the following line:

<TestRoute path='/test' userLoggedIn={ userLoggedIn }/>

And created the TestRoute component as follows:

    const TestRoute = ({ userLoggedIn }) => {
  console.log(userLoggedIn);
  return (
    <Redirect to={{
      pathname: userLoggedIn ? '/yes' : '/no'
    }}/>
  )
}

What I see now is than in the console appears null twice and then the real value for userLoggedIn ... I guess the first time the component receives the null redirects to /no so when the real value "arrives" it doesn't go to /yes as it should...


How can I access the userLoggedIn param I'm passing? Does anyone has a similar example?

Thanks

Ok, after trying several options I found something that works for me an it's even simpler than what I was trying to do.

In the App part where I have the Router I have created a Route that uses conditional coding:

<Route path='/content' component={ userLoggedIn ? Day : LoginPage } />

And that's all I need. If the user is logged in it renders the Day component, if it is not logged in then it redirects to the LoginPage . Maybe it's not the best solution but it works for me.

If someone has a better solution, please let me know.

You access router properties via props.route ie props.route.userLoggedIn .

If your component isn't the top level one you can wrap it in withRouter or access it via the context in v4 but looks like you won't need to.

For navigation check as your userLoggedIn before the user can access the page, I use the onEnter method.

<Route path='/content' onEnter={userLoggedIn} component={Day} />

So your userLoggedIn can be like this

function userLoggedIn(nextState, replace) {
  // check if your user is logged in
  if (localStorage.getItem('isLogged') !== 'true') {
    // block navigation and redirect to login page
    replace({ pathname: '/login', state: { nextPathname: nextState.location.pathname } });
    return true;
  }
  return false;
}

Hope this helps

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