javascript - 使用 promise 获取数据时出错
问题描述
我是诺言的新手,我无法用诺言解决问题。从 API 获取数据后,我必须在函数 loadPosts 中返回一个新状态:
[loadPosts]: (state, index) => {
fetchPosts().then( data => {
return {
...state,
postState : {
postList : data.data
}
}
})
}
这是我的fetchPosts函数:
export const fetchPosts = () => {
console.log("Fetch posts...");
fetch(process.env.REACT_APP_API_URL + '/post')
.then(response => response.json())
.then(data => {
return data
})
.catch(error => console.error(error))
}
我得到“TypeError:无法读取未定义的属性'then'”
据我了解,fetchPosts 函数的第一个和第二个then应该返回一个具有已解析值的承诺,但我得到的是未定义的。
如果我以这种方式更改获取帖子(添加返回):
export const fetchPosts = () => {
console.log("Fetch posts...");
return fetch(process.env.REACT_APP_API_URL + '/post')
.then(response => response.json())
.then(data => {
return data
})
.catch(error => console.error(error))
}
我收到另一个错误: reducer“app”返回未定义。要忽略某个操作,您必须显式返回之前的状态。
我如何使用 promise 来达到我的目标?
谢谢
解决方案
首先,让我们修复您的fetchPosts
功能
export const fetchPosts = () => {
console.log("Fetch posts...");
return fetch(process.env.REACT_APP_API_URL + '/post')
.then(response => response.json())
// the following code is not needed at all
//.then(data => {
// return data
// })
// I prefere not to do the error handling here,
// instead let the caller handle the error
.catch(error => console.error(error))
}
现在 fetch posts 函数实际上返回了一些东西,我只能告诉你,在你的第一个代码片段中的函数内部没有办法返回一个新的状态,其中包含fetchPosts
promise 解析到的帖子。虽然它看起来很像 reducer,所以我建议你看一下redux-thunk,它允许你使用中间件增强 redux 以实现异步行为,然后你可以将函数分发到返回 Promise 的 store。
推荐阅读
- node.js - 如何在基于神经网络的异或门中生成训练数据
- django - 在 django 中显示数据库中的单个项目
- c - 自由函数激活断点
- html - 选择并输入相同的高度
- javascript - 基于 SVG/鼠标位置的定位 Bootstrap 弹出框
- math - 当你不能有 0 和你不能有 1 时,它叫什么?
- nginx - Nginx - 反向代理 nginx: [emerg] mkdir() "/tmp/nginx/cache" failed (2: No such file or directory)
- javascript - 如何在for循环中只打印一个整数而不是整个数组在javascript中的结果?
- java - Spring ThreadPoolTaskExecutor中的maxPoolSize和throttleLimit有什么区别
- c++ - 三元运算符中是否强制复制省略(如果允许)?