javascript - 解决 redux reducer 中的承诺?
问题描述
我有一个使用 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"
我希望解决这个承诺,以便我可以直接访问 fetch 请求返回的值。但我不知道该怎么做?
解决方案
那是因为getQuote
将 Promise 传递给 reducer,而不是返回值。但你知道的。
在这种情况下,您必须异步执行某些操作并调度在异步操作完成时返回值的操作。您不能在传递的 Object 中执行此操作,但可以使用 redux 中间件。有一些库旨在解决诸如redux-thunk
、redux-saga
等问题redux-observable
。
推荐阅读
- python - 从 N 个元组中获取所有值
- react-native - null 不是对象(评估“RNCalendarEvents.authorizationStatus”)
- python - 在 TensorFlow 2.0 中使用 tf.Dataset 进行训练
- click - 如何进行叠加点击
- python - 如何通过右键单击文本小部件来获取整个单词
- angular - Ionic 3 无法改变模态的大小
- material-components - TextInputLayout.OutlinedBox 样式的 boxBackgroundColor 问题
- java - Collections.shuffle 对于 SimClock Random 值不能按预期工作
- android - 使用 Flutter 的 Wifi 细节
- java - 关于带字符数组的 for 循环的基本问题(Java)