使用redux-saga调用异步api

Ilj*_*lja 24 javascript api reactjs redux redux-saga

我正在关注有关帮助程序的redux-saga文档,到目前为止看起来非常简单,但是在执行api调用时我偶然发现了一个问题(因为你会看到文档的链接指向这样的例子)

有一部分Api.fetchUser没有解释,因此我不清楚是否需要处理像axiossuperagent这样的库?还是那个别的东西.和saga效果一样call, put.等价的get, post?如果是这样,他们为什么这样命名?基本上我正试图找出一种正确的方法来对我的api执行简单的post调用,example.com/sessions并传递数据,如{ email: 'email', password: 'password' }

1ve*_*ven 47

Api.fetchUser 是一个函数,应该执行api ajax调用,它应该返回promise.

在您的情况下,此承诺应解析用户数据变量.

例如:

// services/api.js
export function fetchUser(userId) {
  // `axios` function returns promise, you can use any ajax lib, which can
  // return promise, or wrap in promise ajax call
  return axios.get('/api/user/' + userId);
};
Run Code Online (Sandbox Code Playgroud)

然后是传奇:

function* fetchUserSaga(action) {
  // `call` function accepts rest arguments, which will be passed to `api.fetchUser` function.
  // Instructing middleware to call promise, it resolved value will be assigned to `userData` variable
  const userData = yield call(api.fetchUser, action.userId);
  // Instructing middleware to dispatch corresponding action.
  yield put({
    type: 'FETCH_USER_SUCCESS',
    userData
  });
}
Run Code Online (Sandbox Code Playgroud)

call,put是效果创作者的功能.他们没有熟悉GETPOST要求的东西.

callfunction用于创建效果描述,指示中间件调用promise. putfunction创建效果,指示中间件将操作分派给商店.

  • 这是一个非常好的解释,谢谢! (3认同)

Van*_*nic 5

喜欢的东西call,put,take,race是影响创作者的功能.它Api.fetchUser是您自己的函数的占位符,用于处理API请求.

这是loginSaga的完整示例:

export function* loginUserSaga() {
  while (true) {
    const watcher = yield race({
      loginUser: take(USER_LOGIN),
      stop: take(LOCATION_CHANGE),
    });

    if (watcher.stop) break;

    const {loginUser} = watcher || {};
    const {username, password} = loginUser || {};
    const data = {username, password};

    const login = yield call(SessionService.login, data);

    if (login.err === undefined || login.err === null && login.response) {
      yield put(loginSuccess(login.response));
    } else {
      yield put(loginError({message: 'Invalid credentials. Please try again.'}));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在此片段中,SessionService该类是一个实现login处理对API的HTTP请求的方法的类.redux-saga call将调用此方法并将数据参数应用于此方法.在上面的代码段中,我们可以使用相应的方式评估调用和调度loginSuccessloginError操作的结果put.

旁注:上面的代码片段是一个持续监听USER_LOGIN事件的loginSaga ,但在LOCATION_CHANGE发生事件时会中断.这要归功于race效果创作者.