我想知道如何处理 redux saga 中的错误响应,我仍在学习并且正在这样做:
export function* loginUserSaga(action) {
try {
const user = action.payload
const responseData = yield call(loginUser, user);
yield put(succeededLoginRequest(responseData));
} catch (e) {
yield put(failedLoginRequest(e.message));
}
}
是否有其他方法可以处理该问题,以便我可以获得响应而不是错误?正如我在文档中看到的,通常您使用 try catch 向 API 发出请求
最佳答案
Try..catch 通常是可行的方法,但您可以修改您的 loginUser 响应以返回带有响应/错误字段的对象,然后使用条件而不是 try..catch。
这是文档中的示例 ( https://redux-saga.js.org/docs/basics/ErrorHandling.html ):
import Api from './path/to/api'
import { call, put } from 'redux-saga/effects'
function fetchProductsApi() {
return Api.fetch('/products')
.then(response => ({ response }))
.catch(error => ({ error }))
}
function* fetchProducts() {
const { response, error } = yield call(fetchProductsApi)
if (response)
yield put({ type: 'PRODUCTS_RECEIVED', products: response })
else
yield put({ type: 'PRODUCTS_REQUEST_FAILED', error })
}
关于reactjs - 在 redux saga 中获取响应而不是错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54452178/