Javascript 将数据从Saga中的fetch返回到Redux树
在学习如何使用sagas时,我一直在将实际数据输入我的redux商店。上面向有效负载发送Javascript 将数据从Saga中的fetch返回到Redux树,javascript,redux,fetch,redux-saga,Javascript,Redux,Fetch,Redux Saga,在学习如何使用sagas时,我一直在将实际数据输入我的redux商店。上面向有效负载发送responseBody的代码给了我一个Promise对象(因为.json()返回该对象),这非常好,只是我无法访问已解析的Promise。我最终选择了,但这似乎对我不起作用。我试过用几种方法添加。然后(),但没有成功。这似乎完全阻止了发电机的运行 如果我只使用response我会得到一个没有有效负载的response对象。我错过了什么?如何获得正确的负载?您需要等待服务器发回响应 export functi
responseBody
的代码给了我一个Promise对象(因为.json()
返回该对象),这非常好,只是我无法访问已解析的Promise。我最终选择了,但这似乎对我不起作用。我试过用几种方法添加。然后()
,但没有成功。这似乎完全阻止了发电机的运行
如果我只使用
response
我会得到一个没有有效负载的response对象。我错过了什么?如何获得正确的负载?您需要等待服务器发回响应
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;
}
});
}
我遵循了我在这一页上找到的模式,最终为我工作。我不完全理解为什么需要
fetchTree
helper,但是没有它它就无法工作。
谢谢,但这还不够。我得到了“yield是一个保留字”。现在试试吧,我对yield不是很熟悉。我曾想过让这个内部函数也成为一个生成器,但这个函数在获取之后根本不会运行。再试试吧,现在我使用的是async/wait。没有测试,所以我不确定这是否是正确的语法
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;
}
});
}
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,
});
}
}