文章有错误和不合理的地方欢迎小伙伴轻拍看到标题,很多react选手可能就会笑了,这还是问题吗?在函数中触发页面跳转不就的用redux吗!或者redux类似的控件,mbox,dva,rxjs等等,或者自己写个订阅功能的控件,可能就是因为太简单了,网上的解决这个问题的文章才那么少。当我试着用react搭建前端框架,这个问题确实困扰了我好久,当接触到redux就是这redux是正解了。痛点这就是困扰我的问题对fetch()进行封装,并对请求的返回数据做拦截,当捕捉到错误的时候,判断错误的状态码,404时让页面跳转到404页面,当时401时跳转到登录页面,500调整到500页面。 react-router ^4并没有暴露出来history对象,这让非组件内页面跳转变的困难。问题的解决定义storefunction 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”;@withRouterclass 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;当fetch()拦截到错误就可以进行页面调整了如果对redux有疑问,可以看我另一篇文章https://segmentfault.com/a/11… 这就是在函数中通过订阅的方式来实现页面跳转,easy easy !!!小伙伴可以举一反三运用到更多的地方去!!????????????????????如果能帮助到小伙伴的话欢迎点个赞????????????????????????????????????????如果能帮助到小伙伴的话欢迎点个赞????????????????????