首页 > 解决方案 > 使用 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 来达到我的目标?

谢谢

标签: javascriptreactjsreduxpromise

解决方案


首先,让我们修复您的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 函数实际上返回了一些东西,我只能告诉你,在你的第一个代码片段中的函数内部没有办法返回一个新的状态,其中包含fetchPostspromise 解析到的帖子。虽然它看起来很像 reducer,所以我建议你看一下redux-thunk,它允许你使用中间件增强 redux 以实现异步行为,然后你可以将函数分发到返回 Promise 的 store。


推荐阅读