小编典典

在Redux中间件中使用react-router进行重定向

reactjs

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

这是中间件代码

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中

...

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方法不会重定向页面。我肯定代码会通过该部分,因为日志显示


阅读 443

收藏
2020-07-22

共1个答案

小编典典

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

对于: 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),您可以从应用程序中的任何位置导入和使用。

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

2020-07-22