使用redux,react在純函數中觸發react-router-dom頁面跳轉

文章有錯誤和不合理的地方歡迎小夥伴輕拍
看到標題,很多react選手可能就會笑了,這還是問題嗎?在函數中觸發頁面跳轉不就的用redux嗎!或者redux類似的控件,mbox,dva,rxjs等等,或者自己寫個訂閱功能的控件,可能就是因爲太簡單了,網上的解決這個問題的文章才那麼少。當我試着用react搭建前端框架,這個問題確實困擾了我好久,當接觸到redux就是這redux是正解了。

痛點

這就是困擾我的問題

對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 !!!
小夥伴可以舉一反三運用到更多的地方去!!

👍👍👍👍👍如果能幫助到小夥伴的話歡迎點個贊👍👍👍👍👍
👍👍👍👍👍如果能幫助到小夥伴的話歡迎點個贊👍👍👍👍👍

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章