【问题标题】:redux-saga actually consuming dataredux-saga 实际消耗数据
【发布时间】:2017-02-25 02:06:56
【问题描述】:

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

这是我的请求传奇:

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”,它会返回一个承诺。我不能在根据我所见,生成器函数。

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

【问题讨论】:

    标签: javascript react-redux redux-saga


    【解决方案1】:

    因此,互联网上所有(或大部分)示例掩盖的答案是,我需要在包装函数中解决承诺,然后我可以按预期使用生成器。按照这里的例子:

    Building an image gallery using react, redux and 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 };
        }
    }
    

    这仍然允许我像以前一样使用“isomorphic-fetch”,但仍然让它成为一个传奇。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 1970-01-01
      • 2021-12-11
      • 2020-12-18
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      相关资源
      最近更新 更多