26

我正在关注有关帮助程序的 redux-saga 文档,到目前为止,它看起来很简单,但是在执行 api 调用时我偶然发现了一个问题(您将看到指向此类示例的文档链接)

有一部分Api.fetchUser没有解释,因此我不明白这是否是我们需要使用axiossuperagent之类的库来处理的事情?或者是别的什么。并且是传奇效果之类call, put的……等价物get, post吗?如果是这样,他们为什么这样命名?本质上,我试图找出一种正确的方法来在 url 上对我的 api 执行简单的 post 调用example.com/sessions并传递数据,例如{ email: 'email', password: 'password' }

4

2 回答 2

51

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);
};

然后是传奇:

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
  });
}

call,put是效果创建者函数。他们没有熟悉的东西GETPOST要求。

call函数用于创建效果描述,指示中间件调用promise。 put函数创建效果,其中指示中间件将操作分派到商店。

于 2016-08-05T15:07:24.093 回答
6

call, put, take,之类的东西race是效果创建者函数。是您自己处理 API 请求的Api.fetchUser函数的占位符。

这是 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.'}));
    }
  }
}

在此代码段中,SessionService是一个实现login处理对 API 的 HTTP 请求的方法的类。redux-sagacall将调用此方法并将数据参数应用到它。loginSuccess在上面的代码片段中,我们可以loginError使用put.

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

于 2016-08-05T15:11:11.870 回答