使用redux,react在纯函数中触发react-router-dom页面跳转

栏目: 服务器 · 发布时间: 6年前

内容简介:文章有错误和不合理的地方欢迎小伙伴轻拍这就是困扰我的问题对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;

当fetch()拦截到错误就可以进行页面调整了

如果对redux有疑问,可以看我另一篇文章

https://segmentfault.com/a/11...

这就是在函数中通过订阅的方式来实现页面跳转,easy easy !!!

小伙伴可以举一反三运用到更多的地方去!!

:+1::+1::+1::+1::+1:如果能帮助到小伙伴的话欢迎点个赞:+1::+1::+1::+1::+1:

:+1::+1::+1::+1::+1:如果能帮助到小伙伴的话欢迎点个赞:+1::+1::+1::+1::+1:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Head Rush Ajax

Head Rush Ajax

Brett McLaughlin、Eric Freeman、Elisabeth Freeman / O'Reilly Media, Inc. / 2006-03-01 / USD 34.99

Ajax, or Asynchronous JavaScript and XML, is a term describing the latest rage in web development. Ajax is used to create interactive web applications with XML-based web services, and using JavaScript......一起来看看 《Head Rush Ajax》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具