[英]redux-saga actually consuming data
I have read plenty of tutorials regarding 'redux-saga' and understand how to structure my reducers and sagas to execute directly. 我已经阅读了很多有关“ redux-saga”的教程,并且了解如何构造我的reducers和sagas以直接执行。 The problem that I am having is that I don't know to to actually fetch the data requested in a way that returns something I can use. 我遇到的问题是,我不知道是否以返回可以使用的东西的方式实际获取请求的数据。 What do most people use to actually fetch the data requested? 大多数人实际使用什么来获取请求的数据?
Here is my request 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 };
}
}
..The "yield call(fetch..." returns a ReadableStream in Chrome and if I use 'isomorphic-fetch' like I did with redux-thunk it returns a promise. I can't use a promise in a generator function from what I can see. ..“ yield call(fetch ...”)在Chrome中返回一个ReadableStream,如果我像使用redux-thunk一样使用'isomorphic-fetch',它会返回一个promise。我所看到的。
I'm sure this is probably a simple line of code to consume the result, but I can't seem to find it. 我确定这可能是消耗结果的简单代码行,但是我似乎找不到它。 Any help is appreciated! 任何帮助表示赞赏!
So the answer that all of (or most of) the examples on the internet gloss over is that I need to resolve the promise in a wrapper function and then I can use the generator as expected. 因此,Internet上所有(或大多数)示例都掩盖的答案是,我需要在包装函数中解析Promise,然后可以按预期使用生成器。 Following the example here: 遵循此处的示例:
Building an image gallery using react, redux and redux-saga 使用react,redux和redux-saga构建图像库
I split my request generator into two separate methods and fully resolved the promise within the helper function. 我将请求生成器分为两个单独的方法,并在助手函数中完全解决了Promise。 The end result is as follows: 最终结果如下:
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 };
}
}
This still allows me to use 'isomorphic-fetch' as before but still make it into a saga. 这仍然允许我像以前一样使用“同构提取”,但仍然使其成为传奇。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.