gpt4 book ai didi

javascript - 使用 redux-saga 进行异步 api 调用

转载 作者:行者123 更新时间:2023-12-03 13:02:56 25 4
gpt4 key购买 nike

我正在关注redux-saga documentation到目前为止,它似乎非常简单,但是在执行 api 调用时我偶然发现了一个问题(正如您将看到指向此类示例的文档链接)

有一部分 Api.fetchUser 没有解释,因此我不明白这是否是我们需要使用像 axios 这样的库来处理的东西。或superagent ?或者是别的什么。诸如 call、put 等 saga 效果是否与 get、post 等效?如果是这样,为什么他们会这样命名?本质上,我试图找到一种正确的方法来对 url example.com/sessions 处的 api 执行简单的 post 调用,并传递诸如 { email: 'email', password: '密码'}

最佳答案

Api.fetchUser 是一个函数,应该在其中执行 api ajax 调用,并且应该返回 Promise。

就您而言,此 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
});
}

callput 是效果创建器函数。他们不熟悉 GETPOST 请求。

call 函数用于创建效果描述,指示中间件调用 Promise。put 函数创建效果,其中指示中间件将操作分派(dispatch)到存储。

关于javascript - 使用 redux-saga 进行异步 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38791974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com