繁体   English   中英

redux-saga实际消耗数据

[英]redux-saga actually consuming data

我已经阅读了很多有关“ redux-saga”的教程,并且了解如何构造我的reducers和sagas以直接执行。 我遇到的问题是,我不知道是否以返回可以使用的东西的方式实际获取请求的数据。 大多数人实际使用什么来获取请求的数据?

这是我的要求传奇:

import { call } from 'redux-saga/effects';

export function* request(url, method, body) {
    try {
        const result = yield call(fetch, url, { method: method, body: body });
        return {err: null, res: result };
    } catch(error) {
        return {err: error, res: null };
    }
}

..“ yield call(fetch ...”)在Chrome中返回一个ReadableStream,如果我像使用redux-thunk一样使用'isomorphic-fetch',它会返回一个promise。我所看到的。

我确定这可能是消耗结果的简单代码行,但是我似乎找不到它。 任何帮助表示赞赏!

因此,Internet上所有(或大多数)示例都掩盖的答案是,我需要在包装函数中解析Promise,然后可以按预期使用生成器。 遵循此处的示例:

使用react,redux和redux-saga构建图像库

我将请求生成器分为两个单独的方法,并在助手函数中完全解决了Promise。 最终结果如下:

import { call } from 'redux-saga/effects';
import fetch from 'isomorphic-fetch';

const actualRequest = (method, url, body) => {
    return fetch(url, { method: method, body: body })
        .then( response => response.json()
        .then( json => json ));
}

export function* request(method, url, body) {
    try {
        const result = yield call(actualRequest, method, url, body);
        return {err: null, res: result };
    } catch(error) {
        return {err: error, res: null };
    }
}

这仍然允许我像以前一样使用“同构提取”,但仍然使其成为传奇。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM