【问题标题】:React and promise issues with fetch method使用 fetch 方法做出反应和承诺问题
【发布时间】:2020-11-08 19:26:55
【问题描述】:

我是 react 新手,我遇到了一些异步获取数据的问题:

我想获取 github 用户

function fetchUser(username) {
  return fetch(`https://api.github.com/users/${username}`)
    .then(response => response.json())
    .then(data => data)
}

export function getUserData(username) {
  const object =  {
    profile: fetchUser(username),
  }
  console.log(object)
  return object
}

这是我在组件中的方法

componentDidMount() {
  getUserData(this.props.playerOne)
}

但这是我在控制台中得到的

{个人资料:承诺}

我确定我不太了解这个承诺,所以你能帮助我在我的对象中没有 Promise 而是我正在获取的数据吗? (如果我在我的 fetch 中记录数据,我得到了我想要的)

【问题讨论】:

标签: reactjs promise fetch


【解决方案1】:

您可以使此函数异步并等待承诺解决。

export async function getUserData(username) {
  const object =  {
    profile: await fetchUser(username),
  }
  console.log(object)
  return object
}

然后在你的componentDidMount

componentDidMount() {
  getUserData(this.props.playerOne)
    .then((profile) => { this.setState({ profile }) })
}

【讨论】:

  • 为什么我必须这样做,为什么 then() 不能解决我的承诺?
  • 你的promise将在getUserData 函数中被解析(或拒绝),异步函数本身返回一个带有object的promise。在componentDidMount 中,当您调用then 时,您有机会获得object 并将其设置为React 状态。
猜你喜欢
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 2021-01-16
相关资源
最近更新 更多