同构的fetch和redux传奇,如何恰当地调用它?如何使用发电机进行管理?
它告诉我“承诺不是一种功能”。我的问题是,对于同构获取,您必须放置两次才能得到解析结果。我应该怎么做才能用redux saga生成器正确地管理它同构的fetch和redux传奇,如何恰当地调用它?如何使用发电机进行管理?,redux,fetch,react-redux,redux-saga,Redux,Fetch,React Redux,Redux Saga,它告诉我“承诺不是一种功能”。我的问题是,对于同构获取,您必须放置两次才能得到解析结果。我应该怎么做才能用redux saga生成器正确地管理它 import { put, call, takeEvery, takeLatest } from 'redux-saga/effects' import fetch from 'isomorphic-fetch' import errorMessages from './../conf/errorMessages' function *fetchBa
import { put, call, takeEvery, takeLatest } from 'redux-saga/effects'
import fetch from 'isomorphic-fetch'
import errorMessages from './../conf/errorMessages'
function *fetchBalances(address) {
try {
var request = fetch('/api/getBalances/rJnZ4YHCUsHvQu7R6mZohevKJDHFzVD6Zr').then(function(response) {
return response.json();
}). then(function(result) {
// finally my parsed result !
return result;
});
const balances = yield call(request)
yield put({ type: 'GET_BALANCES_SUCCEED', balances: balances})
}
catch(error) {
yield put({ type: 'GET_BALANCES_ERROR', error: error })
}
}
export function* watchGetBalances() {
yield takeEvery('GET_BALANCES', fetchBalances);
}
我可以就此了结,但这是最好的主意吗=/
var request = function() {
return fetch('/api/getBalances/rJnZ4YHCUsHvQu7R6mZohevKJDHFzVD6Zr').then(function(response) {
return response.json();
}). then(function(result) {
return result;
});
}
这里的混淆源于这样一个事实,即传递给
调用的请求
变量
具有承诺
。你想要的是调用
为你履行承诺的效果
换句话说,您已经手动调用了fetch
函数,而不是传递call
一个将调用并返回它的函数
因此,是的,将获取调用封装在一个函数中(例如,callRequest
函数)可能会很有用,但如果这样做,您必须小心编写const response=yield call(callRequest)
,而不是const response=yield call(callRequest())
,这将等同于您编写的内容
一些精度,以防有帮助。从文档中,call
作为其第一个参数接收:
一种生成函数,或作为结果返回承诺或任何其他值的正规函数
让我们看看它是如何工作的
首先是生成函数
const response = yield call(myFunction);
function* myFunction() {
yield delay(1000);
return true;
}
// response === true
然后一个函数返回一些值(不是最有用的,但是…)
最后是一个返回承诺的函数
const response = yield call(callRequest);
function callRequest() {
return fetch(…).then( r => r.json() )
}
// response holds your data
// if the Promise were to be rejected, you could catch
// the error in a try-catch block
const response = yield call(callRequest);
function callRequest() {
return fetch(…).then( r => r.json() )
}
// response holds your data
// if the Promise were to be rejected, you could catch
// the error in a try-catch block