首页 > 解决方案 > 如何在 saga 之前检查服务器响应

问题描述

我正在使用 react-redux 和 redux-saga 来处理我在 React 应用程序中的异步 api 调用。它基本上看起来像这样:
Saga file

function* getStuffEffect(action){
    try{
        yield put({type:'REQUEST',payload:[]});
        //requestFunction(url,type,token) uses axios
        const data = yield call(requestFunciotn,'/profile','GET',action.payload.token)
        if(data.status>=200&data.status<300){
            yield put({type:'SUCCESS',payload:data.data})
        }else{
            yield put({type:'FAILURE',payload:data.message})
        }
    catch(err){
        yield put({type:'FAILURE',payload:err.response.message})
    }
}

export default function* watch(){
    yield all([
        //...other effects,
        takeLatest('GET_STUFF_CONSTANT',getStuffEffect)
    ])
}

存储文件

import {createStore, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootSaga from '../sagas'

const sagaMiddleware = createSagaMiddleware();

const middlewares = [otherMiddleares,sagaMiddleware].filter(Boolean);

const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore);

const store = createStoreWithMiddleware(rootReducer);

sagaMiddleware.run(rootSaga);

export default store;

现在到问题:有时api会以无效令牌引起的401响应。我正在寻找一种方法在它到达上述传奇的流行语并将用户重定向到登录页面之前处理它。我现在可以在组件内部完成,并且在像这样更新之后:

componentDidUpdate(prevProps){
    if(this.props.reducer.someFlag){
        this.props.history.push('/login')
    }
}

但我正在寻找更可靠的解决方案。我有一种感觉,答案应该是使用中间件,但我不知道如何。所以任何帮助都会很棒。tnx。

标签: reactjsreact-reduxredux-saga

解决方案


推荐阅读