A
A
Anton Izmailov2016-04-13 13:55:05
JavaScript
Anton Izmailov, 2016-04-13 13:55:05

How to make friends React-Router onEnter and redux?

I can not figure out the correct authorization in any way.
What should the function that checks the possibility of visiting a certain page by the user look like.
In stock:

  • React 15.0.1
  • Redux 3.4.0
  • React Router 2.x

The user_id and token are also stored in localStorage.
When the application is loaded, the token check is triggered and the result is written to reducer.user
22e9ff6164a24e95ac250d381b3ba604.png
How to build the onEnter function correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-04-21
@maxfarseer

A question of concern to many. I will describe two methods.
1
There is an alternative to onEnter: a component that checks whether to show content or show "access denied", for example. I spied the method itself here , if you understand redux deep enough, then everything is clear.
If not, then I should finish the routing mini-tutorial sometime and come back to this answer.
2
In order to pass "store" in onEnter, you need to wrap the routes in a function.
Looks like this:

export function getRoutes(store) {
  return (
    <div>
      <Route path='/' component={App}>
        <IndexRoute component={Home} />
        <Route path='/admin' component={Admin} onEnter={Admin.onEnter.bind(this,store)}/>
        <Route path='/genre/:genre' component={Genre}>
          <Route path='/genre/:genre/:release' component={Release} />
        </Route>
        <Route path='/list' component={List} />
      </Route>
      <Route path='*' component={NotFound} />
    </div>
  )
}

Here in the Admin component there is an onEnter method (I moved it there, as it is more convenient in my opinion), and in it you can safely check the token. You can also use store.getState() and the like. Don't forget about the standard features of redux - they open up a lot for which it is not necessary to drag libraries.
export default class Admin extends Component {
  static onEnter(store, nextState, replace) {
    const user = store.getState().user
    if (!user) {
      replace('/')
    } 
  }
  render() {
    return (
      <div className='row'>
        <div className='col-md-12'>Раздел /admin</div>
      </div>
    )
  }
}

However, the question is open to me personally. I'm trying to solve a case with a redirect in response to an action ;) As soon as I find a satisfactory solution, I will immediately finish my mini-tutorial

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question