内容简介:文章有错误和不合理的地方欢迎小伙伴轻拍这就是困扰我的问题对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
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Google御用網頁語言Node.js
郭家寶 / 佳魁資訊 / 2013-4-26 / NT 490
這是一本 Node.js 的入門教學,寫給想要學習 Node.js,但沒有任何系統的經驗的開發者。如果你聽說過 Node.js,並被它許多神奇的特性吸引,本書就是為你準備的。 透過閱讀本書,你可以對 Node.js 有全面的認識,學會如何用 Node.js 程式設計,了解事件驅動、非同步式 I/O 的程式設計模式,同時還可以了解一些使用JavaScript 進行函數式程式設計的方法。 ......一起来看看 《Google御用網頁語言Node.js》 这本书的介绍吧!