首页 文章

Errror以承诺获取数据

提问于
浏览
0

我是新的有希望的,我无法解决有希望的问题 . 从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 函数的第一个和第二个应该返回一个带有已解析值的promise但是我得到了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" returned undefined. To ignore an action, you must explicitly return the previous state.

我怎样才能用诺言来实现我的目标?

谢谢

2 回答

  • 0

    1.)您需要返回 fetch() ,以便链接 .then() .

    2.)您需要在reducer中有一个返回 state 的默认大小写 .

  • 0

    首先,让我们修复你的 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解析的帖子的新状态 . 它看起来很像减速器,所以我建议你看一下redux-thunk,它允许你用异步行为的中间件增强redux,然后你可以将函数分派给返回promises的商店 .

相关问题