栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用React Router V4从axios拦截器重定向?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用React Router V4从axios拦截器重定向?

我通过从Component树之外访问Redux
Store并通过注销按钮发送相同的操作来解决了这一问题,因为我的拦截器是在单独的文件中创建的,并且在加载任何Component之前先进行加载。

因此,基本上,我做了以下工作:

index.js
文件中:

//....lots of imports ommited for brevityimport { createStore, applyMiddleware } from 'redux';import reduxThunk from 'redux-thunk';import reducers from './reducers';import { UNAUTH_USER } from './actions/types'; //this is just a constants file for action types.const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);const store = createStoreWithMiddleware(reducers);//Here is the guy where I set up the interceptors!NetworkService.setupInterceptors(store);//lots of pre ommited again...//Please pay attention to the "RequireAuth" below, we'll talk about it laterReactDOM.render(  <Provider store={store}>      <BrowserRouter>          <div>   <Header />   <main className="plan-container">       <Switch><Route exact path="/" component={Landing} /><Route exact path="/login" component={Login} /><Route exact path="/signup" component={Signup} /><Route exact path="/calendar" component={RequireAuth(Calendar)} /><Route exact path="/profile" component={RequireAuth(Profile)} />       </Switch>   </main>          </div>      </BrowserRouter>  </Provider>  , document.querySelector('.main-container'));

并在

network-service.js
文件:

import axios        from 'axios';import { UNAUTH_USER } from '../actions/types';export default {  setupInterceptors: (store) => {    // Add a response interceptor    axios.interceptors.response.use(function (response) {        return response;    }, function (error) {        //catches if the session ended!        if ( error.response.data.token.KEY == 'ERR_EXPIRED_TOKEN') { console.log("EXPIRED TOKEN!"); localStorage.clear(); store.dispatch({ type: UNAUTH_USER });        }        return Promise.reject(error);    });  }};

最后但并非最不重要的一点是,我有一个HOC(高阶组件),它将受保护的组件包装在会话结束时进行实际重定向的位置。这样,当我触发动作类型UNAUTH_USER时,它将我的化简器上的

isLogged
属性设置
session
false
,因此该组件会随时得到通知并为我进行重定向。

require-auth.js
组件文件:

import React, { Component } from 'react';import { connect } from 'react-redux';export default function(ComposedComponent) {    class RequireAuth extends Component {        componentWillMount() { if(!this.props.session.isLogged) {     this.props.history.push('/login'); }        };        componentWillUpdate(nextProps) { if(!nextProps.session.isLogged) {     this.props.history.push('/login'); }        };        render() { return <ComposedComponent {...this.props} />        }    }    function mapStateToProps(state) {        return { session: state.session };    }    return connect(mapStateToProps)(RequireAuth);}

希望有帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号