【问题标题】:Cannot console.log fetch results无法 console.log 获取结果
【发布时间】:2018-11-26 20:24:54
【问题描述】:

我正在尝试使用 fetch() 进行 API 调用。

我知道 fetch() 返回一个 Promise,应该使用 .thenawait 处理。 result.json() 也是如此 遵循本教程 http://www.reactnativeexpress.com/networking,我到达 fetchRoute()function。函数内部的console.log(route) 永远不会被调用。

我尝试返回 console.log(fetchRoute(this.state.userLocation, text)),但它仍然返回一个 Promise。

我在 Stack Overflow 上阅读了另一个问题(抱歉,找不到链接了),他们说试试这样:

getRouteHandler = (text) => { fetchRoute(this.state.userLocation, text).then(json => console.log(json));

不过,我无法记录获取结果。任何人都知道可能出了什么问题?以下是相关代码:

const fetchRoute = async (ori, dest) => {
  let origin = ori.latitude+','+ori.longitude; 
  let destination = encodeURIComponent(dest); 
  const key = "MyAPIKey";
  const URL = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&key=${key}`;

  try{
    const response = await fetch(URL)
    const route = await response.json()
    console.log(route)
    return route
  }catch(e){
    return e
  }
}

export default class App extends Component{

 state = {
    userLocation: null,
    route: [],
  }

  getRouteHandler = (text) => {
    fetchRoute(this.state.userLocation, text).then(json => console.log(json));
}

【问题讨论】:

  • .then 是要走的路。 Still, I couldn't log the fetch results 它在那里记录了什么? (您确定请求正确吗?检查网络选项卡,也许?)
  • 根本没有结果。由于某种原因,它不会在控制台上打印任何内容。我还尝试放随机日志,看看它是否进入那里,例如下面的代码。仍然没有结果。 ` const response = await fetch(URL) const route = await response.json() console.log("检查是否输入的随机字符串")`
  • 就像我说的,检查您的网络选项卡 - 可能是请求没有通过,而不是您的代码有问题。您也可以在尝试 await .json() 之前检查 response.ok
  • 在调用 fetchRoute 之前编写 debugger; 并使用检查器运行代码。您将看到代码逐行运行。我用存根 API 运行了你的代码,它适用于 async/await 部分,在我看来,getRouteHandler 没有被调用。
  • 有异常吗?如果是这样,console.log(route) 将不会被触发。而console.log(json) 会输出异常。

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

有时,如果您要获取大量数据,则需要一段时间才能记录下来。例如,在过去的项目中,我从中获取的 api 有近 500 万条记录。花了几分钟才能在控制台中看到任何内容。

【讨论】:

  • 另一个旁注;我注意到在添加文本 cmets 时它不起作用。示例:console.log(JSON.stringify(data));console.log(JSON.stringify("test data", data));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 2013-12-07
  • 2020-04-17
  • 2021-05-15
  • 2012-04-26
  • 1970-01-01
相关资源
最近更新 更多