R
R
RomanSS2017-02-06 14:16:20
React
RomanSS, 2017-02-06 14:16:20

React and react-router, how to block the execution of a route?

Tell me, there is such a router code:

function requireTest(nextState, replaceState,cb) {
 // псевдокод  
 Если нет ID новости { 
    cb();
  } 
  иначе {
    не вызываем колбек
  }
}

export default (
     <Route path="" component={App}>
     	<IndexRoute component={Index} />
     	<Route onEnter={requireTest} path="test/(:id/)" component={Test} />
     </Route>
)

If you use cb() in requireTest , you can block the execution of the router. The router will wait for cb() to complete. Let's say I want to change the link c site -> site/test/1 without redirecting. What happens inside the router code when you do not call cb (), what problems can arise with this?
And the second question, is there a way to make one general onEnter so that it runs for all routers? There is a certain code that you want to execute when the link changes, but in order to catch it, each router will have to set onEnter, but this also has a problem, when the link changes, several onEnters can be executed, maybe there is one common one?
There is a common event browserHistory.listen( location => {}); but there is no access to nextState, replaceState,cb

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrei Smirnov, 2017-02-14
@pinebit

I'm not sure I fully understand the problem, but if it helps - very similar to what I did to check the user (logged in or not):

path: '/portal',
      getComponent(location, cb) {
        System.import('containers/Portal').then(loadModule(cb)).catch(errorLoading);
      },
      onEnter: (nextState, replace) => checkLoggedInState(store, nextState, replace),
      childRoutes: [
        {
          path: 'dashboard',
          ...
        },
          path: 'products',
          ...
        },
        ...

function checkLoggedInState(store, nextState, replace) {
  if (!isLoggedIn(store)) {
    replace({
      pathname: '/login',
      state: {nextPathname: nextState.location.pathname}
    })
  }
}

The point is that onEnter on the "parent" path (all other application paths start from it), checks that the user is logged in (checkLoggedInState) and if not, makes a redirect to /login, for example.
All other child containers no longer define their onEnter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question