为什么我的 redux-saga 是异步的
Why my redux-saga is async
在我的 React-Native 应用程序中,我编写了一个用户登录组件,该组件将用户名和哈希发送到服务器,将哈希与数据库中的哈希进行比较,然后 return 结果。我实现了 using redux-saga
:
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action);
yield put({type: types.USER_FETCH_SUCCEEDED, user});
} catch (e) {
yield put({type: types.USER_FETCH_FAILED, message: e.message});
}
}
export function* watchFetchUser() {
yield* takeEvery(types.USER_FETCH_REQUESTED, fetchUser);
}
export default function* rootSaga() {
yield fork(watchFetchUser);
// ...
}
我预计 const user
将包含来自 API 的响应,之后将包含 运行 yield put({type: types.USER_FETCH_SUCCEEDED, user})
。但是yield call(Api.fetchUser, action)
之后user
就是undefined
。但是 Api.fetchUser
return 的正确反应。
而且我找不到我的错误在哪里。为什么 const user = yield call(Api.fetchUser, action)
的结果是 undefined
而 Api.fetchUser
return 正确响应后?
fetchUser(action) {
const url = `${apiUrls.LOGIN_URL}`;
fetch(url, 'POST', action.user)
.then(response => response.json())
.then(res => res)
}
您没有从 fetchUser 函数返回承诺。应该是
fetchUser(action) {
const url = `${apiUrls.LOGIN_URL}`;
return fetch(url, 'POST', action.user)
.then(response => response.json())
.then(res => res)
}
在我的 React-Native 应用程序中,我编写了一个用户登录组件,该组件将用户名和哈希发送到服务器,将哈希与数据库中的哈希进行比较,然后 return 结果。我实现了 using redux-saga
:
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action);
yield put({type: types.USER_FETCH_SUCCEEDED, user});
} catch (e) {
yield put({type: types.USER_FETCH_FAILED, message: e.message});
}
}
export function* watchFetchUser() {
yield* takeEvery(types.USER_FETCH_REQUESTED, fetchUser);
}
export default function* rootSaga() {
yield fork(watchFetchUser);
// ...
}
我预计 const user
将包含来自 API 的响应,之后将包含 运行 yield put({type: types.USER_FETCH_SUCCEEDED, user})
。但是yield call(Api.fetchUser, action)
之后user
就是undefined
。但是 Api.fetchUser
return 的正确反应。
而且我找不到我的错误在哪里。为什么 const user = yield call(Api.fetchUser, action)
的结果是 undefined
而 Api.fetchUser
return 正确响应后?
fetchUser(action) {
const url = `${apiUrls.LOGIN_URL}`;
fetch(url, 'POST', action.user)
.then(response => response.json())
.then(res => res)
}
您没有从 fetchUser 函数返回承诺。应该是
fetchUser(action) {
const url = `${apiUrls.LOGIN_URL}`;
return fetch(url, 'POST', action.user)
.then(response => response.json())
.then(res => res)
}