reactjs - 如何在 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。
解决方案
推荐阅读
- flutter - 如何在 Flutter 中的 OnChange 事件中清除 Textfield 并将焦点返回到同一个 Textfield 控制器?
- c++ - 重启自己的qt应用
- javascript - 如何将作为请求接收的 JSON 数据传递给外部变量?
- html - 如何在 td 内有 Div 的表中添加 Datatable
- python - 从看似没有统一分隔符的字符串中提取值
- c# - 在 C# 中使用 Windows.Forms 创建一个窗口
- bash - Tmux 启动脚本窗口未正确拆分
- ansible - 如何分别为每个服务器运行 Ansible 任务
- powershell - 一种让函数在特定时间运行的优雅方式
- python - 如何异步中止 docplex 中的求解?