Redirect using react-router in redux middleware

后端 未结 2 1571
北荒
北荒 2021-02-10 14:45

I\'ve created a middleware that checks if a request returns an invalid access response. If the status is a 401, I want to redirect the user to the login page

Here\'s the

2条回答
  •  情话喂你
    2021-02-10 15:12

    if you prefer Redux style actions, the library also provides a set of action creators and a middleware to capture them and redirect them to your history instance.

    for: push(location), replace(location), go(number), goBack(), goForward()

    You must install routerMiddleware for these action creators to work.

    import { routerMiddleware, push } from 'react-router-redux'
    
    // Apply the middleware to the store
    const middleware = routerMiddleware(browserHistory)
    const store = createStore(
      reducers,
      applyMiddleware(middleware)
    )
    
    // Dispatch from anywhere like normal.
    store.dispatch(push('/foo'))
    

    Also React Router provides singleton versions of history (browserHistory and hashHistory) that you can import and use from anywhere in your application.

    import { browserHistory } from 'react-router'
    
    if(action.payload != undefined && action.payload.status==401){
            browserHistory.push('login');
            console.log('session expired'); 
    }
    

    btw for check auth you may use onEnter or redux-auth-wrapper

提交回复
热议问题