内容简介:文章有错误和不合理的地方欢迎小伙伴轻拍这就是困扰我的问题对fetch()进行封装,并对请求的返回数据做拦截,当捕捉到错误的时候,判断错误的状态码,404时让页面跳转到404页面,当时401时跳转到登录页面,500调整到500页面。
文章有错误和不合理的地方欢迎小伙伴轻拍
痛点
这就是困扰我的问题
对fetch()进行封装,并对请求的返回数据做拦截,当捕捉到错误的时候,判断错误的状态码,404时让页面跳转到404页面,当时401时跳转到登录页面,500调整到500页面。
react-router ^4并没有暴露出来history对象,这让非组件内页面跳转变的困难。
问题的解决
定义store
function navTo(state = "/", action) {
switch (action.type) {
case 'NAV_TO':
return action.path;
default:
return state
}
}
let store = createStore(combineReducers({navTo}));
export default store;
fetch()状态拦截代码
import store from "../../redux/store";
fetch(builUrl(url, params), requestInit)
.then(data => {
return data.json()
}).catch(e => {
const status = e.name;
if (status === 401) {
store.dispatch({type: 'NAV_TO', path: '/login'});
return;
}
if (status === 403) {
store.dispatch({type: 'NAV_TO', path: '/exception/403'});
return;
}
if (status <= 504 && status >= 500) {
store.dispatch({type: 'NAV_TO', path: '/exception/500'});
return;
}
if (status >= 404 && status < 422) {
store.dispatch({type: 'NAV_TO', path: '/exception/404'});
return;
}
})
app.js实现对store的订阅,并跳转页面
import React, {Component} from 'react';
import store from './app/common/redux/store.js'
import {withRouter} from "react-router-dom";
@withRouter
class App extends Component {
constructor(props) {
super(props);
store.subscribe(() => {
this.props.history.push(store.getState().navTo);
});
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default App;
这就是在函数中通过订阅的方式来实现页面跳转,easy easy !!!
小伙伴可以举一反三运用到更多的地方去!!
:+1::+1::+1::+1::+1:如果能帮助到小伙伴的话欢迎点个赞:+1::+1::+1::+1::+1:
:+1::+1::+1::+1::+1:如果能帮助到小伙伴的话欢迎点个赞:+1::+1::+1::+1::+1:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Web API的设计与开发
[日] 水野贵明 / 盛荣 / 人民邮电出版社 / 2017-6 / 52.00元
本书结合丰富的实例,详细讲解了Web API的设计、开发与运维相关的知识。第1章介绍Web API的概要;第2章详述端点的设计与请求的形式;第3章介绍响应数据的设计;第4章介绍如何充分利用HTTP协议规范;第5章介绍如何开发方便更改设计的Web API;第6章介绍如何开发牢固的Web API。 本书不仅适合在工作中需要设计、开发或修改Web API的技术人员阅读,对想了解技术细节的产品经理、运维人......一起来看看 《Web API的设计与开发》 这本书的介绍吧!