内容简介:文章有错误和不合理的地方欢迎小伙伴轻拍这就是困扰我的问题对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:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Azure Document DB 存储过程、触发器、自定义函数的实现
- 触发器
- jQuery 自动触发事件实例
- Oracle触发器详细讲解
- react事件系统之事件触发
- 窗口实用触发器:ContinuousEventTimeTrigger
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
移动应用的设计与开发
[美] 弗林 (Brian Fling) / 马晶慧 / 电子工业出版社 / 2010-5 / 59.80元
本书全面介绍了如何在移动设备上设计和开发应用程序。书中从介绍移动产业的生态环境和移动媒体开始,阐述产品策划的方法、产品架构、视觉设计和产品类型的选择,并详细描述了产品实现过程中所用到的一些技术、工具和概念,最后还简单介绍了如何获得利润和降低成本,肯定了iPhone在移动设备发展史上起到的巨大推动作用。本书不仅能让读者了解到移动设计和开发的知识,更重要的是,它揭示了移动开发的代价高昂、标准混乱的根本......一起来看看 《移动应用的设计与开发》 这本书的介绍吧!