【发布时间】:2018-12-05 22:28:04
【问题描述】:
我是新的承诺,我无法解决承诺的问题。 从 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: Cannot read property 'then' of undefined"
据我了解,fetchPosts 函数的第一个和第二个 then 应该返回一个具有已解析值的承诺,但我却得到了 undefined。
如果我以这种方式更改获取帖子(添加返回):
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的承诺。 -
谢谢@Jaime,我该如何回报承诺?
-
不确定在 React 中是如何工作的。尝试谷歌搜索您的第二个错误。
-
return fetch(........承诺就像一条链条,如果你不回报你的承诺,你就会打破这个链条。
标签: javascript reactjs redux promise