本文介绍了'yield' 表达式只允许在生成器主体中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using redux-saga to fetch server api data.My question is that I'm trying to design following code.

然而,被注释掉的 yield put(get01Action(members)); 有以下语法错误.

However yield put(get01Action(members)); which is commented out has following Syntax error.

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
    }
}

请给我一些建议.

谢谢.

推荐答案

可以使用call effect进行axios call,然后就可以使用put了.

you can use call effect to make axios call and then you will be able to use put.

现在它不起作用,因为您在 promise 的回调中使用了 yield.

right now it's not working because you are using yield inside call back of promise.

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)
    }
}

这篇关于'yield' 表达式只允许在生成器主体中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:37