export function* onFetchTree() {
yield takeLatest('FETCH_TREE', function* () {
try {
const response = yield call(fetch, '/myApi/user', {
method: 'GET',
headers: {
accept: 'application/json'
}
})
const responseBody = response.json();
yield put({ type: 'SET_TREE', payload: responseBody });
} catch (e) {
// yield put(fetchFailed(e));
return;
}
});
}
学习使用传奇,坚持将实际数据存入我的redux商店。将responseBody
发送到有效负载的上述代码为我提供了一个Promise对象(因为.json()
返回了这个),这很好,除了我无法访问已解析的Promise。我最终选择了What does [[PromiseValue]] mean in javascript console and how to do I get it,但这似乎对我不起作用。我试过在几个方面添加.then()
,没有运气。它似乎阻止了发电机功能的运行。
如果我只使用response
,我会得到一个没有有效负载的Response对象。我在这里错过了什么?我如何获得正确的有效载荷?
您需要等待服务器发回响应。
export async function* onFetchTree() {
yield takeLatest('FETCH_TREE', function* () {
try {
const response = yield call(fetch, '/myApi/user', {
method: 'GET',
headers: {
accept: 'application/json'
}
})
const responseBody = await response.json()
yield put({ type: 'SET_TREE', payload: responseBody )}
};
} catch (e) {
// yield put(fetchFailed(e));
return;
}
});
}
我按照我在这个页面上找到的模式,最终为我工作。我不完全理解为什么需要fetchTree
助手,但没有它就行不通。 https://www.sigient.com/blog/managing-side-effects-with-redux-saga-a-primer-1
function fetchJson(url) {
return fetch(url, {
method: 'GET',
headers: {
accept: 'application/json'
}
})
.then(response => {
if (!response.ok) {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
return response.json();
});
}
function fetchTree() {
return fetchJson('/myApi/user');
}
export function* onFetchTree() {
try {
const tree = yield call(fetchTree);
yield put({ type: 'SET_TREE', payload: tree });
} catch (e) {
yield put({
type: 'ERROR',
payload: e,
error: true,
});
}
}