只允许在生成器主体中使用'yield'表达式



我正在使用redux-saga来获取服务器 api 数据。 我的问题是我正在尝试设计以下代码。

但是yield put(get01Action(members));注释掉的内容具有以下语法错误。

A 'yield' expression is only allowed in a generator body.

我不知道如何管理它。

import '@babel/polyfill';
import { fork, take, put } from 'redux-saga/effects';
import axios from "axios";
export function* rootSaga(){
yield fork(fetch01);
yield fork(fetch02);
}
function* fetch01() {
while (true){
yield take('FETCH01_REQUEST');
axios.get('/api/members')
.then(function (response) {
// handle success
let members = response.data.data;
// yield put(get01Action(members));
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
}
function* fetch02() {
....
}
function get01Action(members){
return {
type: 'GET_MEMBERS',
member_id: 0,
members: members
}
}

请给我一些建议。

谢谢。

因为您的生成器fetch01是同步的,但您正在等待Promise被重新创建。

yield不能包装在生成器以外的其他函数中。

你可以像这样让生成器async

export async function* rootSaga(){
yield await fork(fetch01);
yield fork(fetch02);
}
async function* fetch01() {
while (true) {
yield take('FETCH01_REQUEST');
try {
const response = await axios.get('/api/members');
// handle success
let members = response.data.data;
yield put(get01Action(members));
} catch (error) {
// handle error
console.log(error);
} finally {
// always executed
}
}
}

你可以使用调用效果来调用 axios,然后你就可以使用 put。

现在它不起作用,因为您正在使用 yield 内部回调承诺。

function* fetch01() {
while (true){
try {
yield take('FETCH01_REQUEST');
const response = yield call(axios.get, '/api/members');
yield put(get01Action(response.data.data))
} catch(err) {
console.error(err)
}
}

最新更新