【发布时间】:2018-11-26 20:24:54
【问题描述】:
我正在尝试使用 fetch() 进行 API 调用。
我知道 fetch() 返回一个 Promise,应该使用 .then 或 await 处理。 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