以下代码将发布请求发送到API,然后存储API的响应。存储的对象是实现的承诺,而不是主体。我虽然正确地使用了.then,但是对于get请求,类似的东西也可以使用。
每次发出发布请求时都会调用以下传奇。它包含从发布到调用到对reducer调用的所有内容。
function* setData(action) {
const url = action.payload.url;
const data_obj = action.payload.data;
console.log(action);
try {
const json = fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data_obj)
})
.then(statusHelper)
.then(response => response.json());
yield put({ type: "DATA_SENT", payload: json });
}
catch (e)
{
yield put({ type: ERROR_OCCURED, payload: { error : {message: "An Error occured sending HIT data. Please try again later"}}});
}
}
下面是statusHelper函数。它来自另一个SO答案(我将在链接中进行编辑)。
function statusHelper (response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
我认为您的问题在这里
.then(response => response.json());
response.json()
也会返回一个承诺。
您需要关闭.then
调用并返回数据。
提取后我错过了产量。这是我的解决方案
json()