Javascript 如何使用redux saga发出异步请求
我正试图请求获得一些关于redux传奇的用户信息。 到目前为止,我已经:Javascript 如何使用redux saga发出异步请求,javascript,redux,redux-saga,Javascript,Redux,Redux Saga,我正试图请求获得一些关于redux传奇的用户信息。 到目前为止,我已经: function* getUserDetails() { const userDetails = axios.get('http://localhost:3004/user').then(response => response) yield put({ type: 'USER_DATA_RECEIVED', user: userDetails}) } function* actionWatcher() {
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(),
]);
}
但是当我注销时,用户
会返回为未定义
或承诺
。因此,我尝试添加yield call(这里是axios的东西)
但这似乎也不起作用
有人有什么想法吗a)如何正确使用
呼叫?和b)如何使用动作通过有效负载?在您的案例中使用呼叫效果的正确方法是:
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})
}
您是否尝试将yield put()
放入.then()
?但在then块中我该怎么做?在thunk中,您只需使用有效负载启动操作,减速机侦听,它处于您的状态。我不熟悉redux,但逻辑上说您应该这样做。然后(response=>{yield put({type:'USER\u DATA\u RECEIVED',USER:response})
产量是保留字
@Mirakurun和redux传奇我通常没有在承诺的然后
块中使用效果,call
效果负责从promise中检索响应值。您可能还希望将该调用包装为try catch
,具体取决于您处理错误的方式。提到call
将根据已解决的承诺恢复生成器,但在被拒绝的承诺上抛出错误。