reactjs - '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
}
}
}
推荐阅读
- view - Drupal 8 - 过滤特定用户的视图以将内容相关字段与用户名匹配
- git - 合并到文件名已更改且旧名称在拉出的分支中使用的分支
- navigation - 问:没有 NavigationButton 的导航
- java - 如何在多个类中重复使用 arg4j 中的重复参数?
- react-native-android - 如何在 React Native 0.60.0 中使用 React Navigation?
- amp-html - AMP 轮播滑块中的 AMP 表单
- eclipse - 为什么 Eclipse Jetty Plugin 看不到 org.json.simple.parser.ParseException?
- android - 在 CardView 中移动 ImageView
- asp.net-core - Serilog ILogger Provider 不响应配置
- redirect - 在 directadmin 中隐藏端口号 (:2222)