[英]Redux-Thunk: async dispatch is not working
我正在尝试在react native中构建一个应用程序,该应用程序假设用户接受两个输入,然后对api进行查询并获取有关两个输入的信息。 我一直在使用redux
和redux-thunk
遇到麻烦,尤其是async
操作。
这是我的应用程序中我特别遇到麻烦的代码
export const fetchData = url => {
console.log("start Fetching");
return async dispatch => { // this is where the problem is
dispatch(fetchingRequest());
try {
const response = await fetch("https://randomuser.me/api/?results=10");
const json = await response.text();
if (response.ok) {
dispatch(fetchingSuccess(json));
console.log("JSON", json);
} else {
console.log("fetch did not resolve");
}
} catch (error) {
dispatch(fetchingFailure(error));
}
};
console.log("Fetched data");
};
在调试该函数后,我最后发现,当fetchData
函数被调用时,该函数将执行,但是返回的async dispatch
具有undefined
行为。
调用该函数时,调试器中的输出应为
start Fetching
JSON file information/Error
但是调试器中的输出实际上是
start Fetching
为什么不简单地使用Promise语法?
fetch("https://randomuser.me/api/?results=10")
.then(response => {
if (response.ok) {
// do something
}
})
.catch(e => console.log('fetch did not resolve'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.