【问题标题】:Redirect using react-router in redux middleware在 redux 中间件中使用 react-router 重定向
【发布时间】:2016-10-23 20:37:43
【问题描述】:

我创建了一个中间件,用于检查请求是否返回无效的访问响应。如果状态是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 方法不会重定向页面。我确信代码会通过该部分,因为日志正在显示

【问题讨论】:

  • 看看下面我的回答,希望对你有所帮助。

标签: reactjs react-router react-jsx react-redux


【解决方案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'); 
}

顺便说一句,您可以使用onEnterredux-auth-wrapper 来检查身份验证

【讨论】:

    【解决方案2】:

    使用onEnter react-router 方法。调用一个函数来检查访问。示例:

    function checkAccess() {
       //some logic to check 
        if(notAuthorized){ window.location.href= "/login"; }
      }
    

    【讨论】:

    • 问题是关于如何根据发送到商店的特定操作重新路由,这并不严格附加到输入路由的过程。此外,onEnter 函数的第二个参数是replace,这是指定要前往的新路线的正式方式。
    猜你喜欢
    • 2020-09-02
    • 2019-07-30
    • 1970-01-01
    • 2018-01-07
    • 2018-02-18
    • 1970-01-01
    • 2019-03-01
    • 2017-11-10
    相关资源
    最近更新 更多