如何使用Redux-Saga发出异步请求

时间:2019-01-07 07:58:54

标签: javascript redux 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)如何通过动作传递有效载荷?

1 个答案:

答案 0 :(得分:2)

在您的情况下,使用 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})
}
相关问题