在 redux 中间件中使用 react-router 重定向 [英] Redirect using react-router in redux middleware

查看:84
本文介绍了在 redux 中间件中使用 react-router 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个中间件,用于检查请求是否返回无效的访问响应.如果状态是 401,我想将用户重定向到登录页面

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

这是中间件代码

import React from 'react';
import { push, replace } from 'react-router-redux';

const auth_check = ({ getState }) =>  {
  return (next) => (action) => {
    if(action.payload != undefined && action.payload.status==401){
        push('login');
        console.log('session expired'); 
    }
    // Call the next dispatch method in the middleware chain.
    let returnValue = next(action);

    return returnValue
  }
}

export default auth_check;

将其包含在 index.js 中

Including it in index.js

...

const store = createStore(reducers, undefined, 
            compose(
                applyMiddleware(promise,auth_check)
                )
            );
const history = syncHistoryWithStore(browserHistory, store);

ReactDOM.render(
  <Provider store={store}>
    <Router history={history} routes={routes} />
  </Provider>
  , document.querySelector('.app'));

push 方法不会重定向页面.我确信代码会通过该部分,因为日志正在显示

The push method does not redirect the page. I am sure that the code goes through that section since the log is showing

推荐答案

如果您更喜欢 Redux 样式的动作,该库还提供了一组动作创建者和一个中间件来捕获它们并将它们重定向到您的历史实例.

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()

您必须安装 routerMiddleware 才能使这些操作创建者工作.

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'))

React Router 还提供历史记录的单例版本(browserHistory 和 hashHistory),您可以从应用程序的任何位置导入和使用.

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'); 
}

顺便说一句,您可以使用 onEnterredux-auth-wrapper

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

这篇关于在 redux 中间件中使用 react-router 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆