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
是效果创建者函数。他们没有熟悉的东西GET
或POST
要求。
call
函数用于创建效果描述,指示中间件调用promise。
put
函数创建效果,其中指示中间件将操作分派到商店。