【问题标题】:Errror fetching data with promise使用 promise 获取数据时出错
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 这个答案帮助我解决了问题。我有反转控制流,因为我没有找到异步调用后返回数据的方法。因此,我通过 redux-thunk 调度 API 调用以获取数据,并在使用“then”之后调度另一个调用来更新状态。
【解决方案2】:

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

2.) 你需要在你的 reducer 中有一个默认情况,它返回 state

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2022-01-26
    • 2021-09-28
    相关资源
    最近更新 更多