我有一个使用redux的reactjs项目。我正在进行以下获取请求:
function fetchQuote() {
return fetch("http://localhost:8080/quote").then(function (response) {
if (!response.ok) {
throw Error(response.statusText);
}
// Read the response as json.
return response;
})
.then(function (response2) {
// Do stuff with the JSON
return response2.text();
})
.then(function (response3) {
return response3
})
.catch(function (error) {
console.log('Looks like there was a problem: \n', error);
})
}
我想使用此函数返回项目后端的字符串值。我通过我的动作创建者访问此功能,如下所示:
export const getQuote = () => ({ type: 'GET_QUOTE', payload: fetchQuote() });
然后转到减速器:
const quoteReducer = (state = { title: 'test', id: 1 }, action) => {
switch (action.type) {
case GET_QUOTE:
console.log(action);
return [...state, action.payload];
default:
return state;
}
};
然而,当我console.log(action)
时,我得到以下内容:
{type: "GET_QUOTE", payload: Promise}
payload
:
Promise
__proto__
:
Promise
[[PromiseStatus]]
:
"resolved"
[[PromiseValue]]
:
"tes11t"
type
:
"GET_QUOTE"
我希望解析promise,以便我可以直接访问fetch请求返回的值。但我不确定该怎么做?
答案 0 :(得分:1)
那是因为getQuote
将Promise传递给reducer,而不是返回值。但你知道。
这是一种情况,您必须异步进行某些操作并分派操作,以便在>完成时返回异步操作的值。您无法在通过的对象中执行该操作,但可以使用redux中间件。有一些图书馆旨在解决这个问题,例如redux-thunk
,redux-saga
,redux-observable
等。