如何使用 redux-saga 发出异步请求
How to make an async request using redux-saga
我正在尝试请求使用 redux sagas 获取一些用户信息。
到目前为止我有:
function* getUserDetails() {
const userDetails = axios.get('http://localhost:3004/user').then(response => response)
yield put({ type: 'USER_DATA_RECEIVED', user: userDetails})
}
function* actionWatcher() {
yield takeLatest('GET_USER_DATA', getUserDetails)
}
export default function* rootSaga() {
yield all([
actionWatcher(),
]);
}
但是当我注销时 user
返回为 undefined
或 Promise<pending>
。所以我尝试添加 yield call(axios stuff in here)
但这似乎也不起作用
有人知道 a) 如何正确使用 call
吗?和 b) 如何通过操作传递有效负载?
在您的案例中使用 call 效果的正确方法是:
function* getUserDetails() {
const userDetails = yield call(axios.get, 'http://localhost:3004/user');
yield put({ type: 'USER_DATA_RECEIVED', user: userDetails})
}
call的第一个参数是您要调用的函数,后续参数是您要传递给被调用函数的参数。
改进版
对外部 API 的调用总是会出错,因此通过在 Axios 调用周围包装一个 try/catch 块来防止这种情况是一个很好的做法。
例如,在 catch 块中,您可以分派发出错误信号的操作,您可以使用它向用户显示错误消息。
function* getUserDetails() {
let userDetails;
try {
userDetails = yield call(axios.get, 'http://localhost:3004/user');
} catch (error) {
yield put({ type: 'USER_DATA_ERROR', error });
return;
}
yield put({ type: 'USER_DATA_RECEIVED', user: userDetails})
}
我正在尝试请求使用 redux sagas 获取一些用户信息。 到目前为止我有:
function* getUserDetails() {
const userDetails = axios.get('http://localhost:3004/user').then(response => response)
yield put({ type: 'USER_DATA_RECEIVED', user: userDetails})
}
function* actionWatcher() {
yield takeLatest('GET_USER_DATA', getUserDetails)
}
export default function* rootSaga() {
yield all([
actionWatcher(),
]);
}
但是当我注销时 user
返回为 undefined
或 Promise<pending>
。所以我尝试添加 yield call(axios stuff in here)
但这似乎也不起作用
有人知道 a) 如何正确使用 call
吗?和 b) 如何通过操作传递有效负载?
在您的案例中使用 call 效果的正确方法是:
function* getUserDetails() {
const userDetails = yield call(axios.get, 'http://localhost:3004/user');
yield put({ type: 'USER_DATA_RECEIVED', user: userDetails})
}
call的第一个参数是您要调用的函数,后续参数是您要传递给被调用函数的参数。
改进版
对外部 API 的调用总是会出错,因此通过在 Axios 调用周围包装一个 try/catch 块来防止这种情况是一个很好的做法。
例如,在 catch 块中,您可以分派发出错误信号的操作,您可以使用它向用户显示错误消息。
function* getUserDetails() {
let userDetails;
try {
userDetails = yield call(axios.get, 'http://localhost:3004/user');
} catch (error) {
yield put({ type: 'USER_DATA_ERROR', error });
return;
}
yield put({ type: 'USER_DATA_RECEIVED', user: userDetails})
}