在 React-Native 中执行时获取 API 调用不起作用
Fetch API call not working when executed in React-Native
我正在尝试在 React Native 中进行提取 API 调用:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
TouchableHighlight,
View
} from 'react-native';
class AwesomeProject extends Component {
render() {
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>
<TextInput
placeholder="Enter Text to Be Validated"
style={{height: 65, width: 275, fontSize: 22}}
onSubmitEditing={(event) => {
var apiKey = "someAPIKey"
var encodedAddress = encodeURIComponent(event.nativeEvent.text)
fetch("https://maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddress + "&key=" + apiKey)
.then(response => response.json())
.then(json => {
if (json.status === "OK") {
console.log(json.results.formatted_address)
}
else {
console.log("Invalid")
}
})
.catch(err => console.err(err))
}}
/>
</View>
);
}
但是,注册到 onSubmitEditing 的回调仅在 React-Native 外部测试时有效。有人知道解释吗??
谢谢!!
尝试
if (json.status === "OK") {
console.log(json.results[0].formatted_address)
}
我进行了一些挖掘,发现返回的 JSON 具有状态 属性 和一个结果数组。您可以使用 results[0]
.
访问该结果数组中的第一项
我正在尝试在 React Native 中进行提取 API 调用:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
TouchableHighlight,
View
} from 'react-native';
class AwesomeProject extends Component {
render() {
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>
<TextInput
placeholder="Enter Text to Be Validated"
style={{height: 65, width: 275, fontSize: 22}}
onSubmitEditing={(event) => {
var apiKey = "someAPIKey"
var encodedAddress = encodeURIComponent(event.nativeEvent.text)
fetch("https://maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddress + "&key=" + apiKey)
.then(response => response.json())
.then(json => {
if (json.status === "OK") {
console.log(json.results.formatted_address)
}
else {
console.log("Invalid")
}
})
.catch(err => console.err(err))
}}
/>
</View>
);
}
但是,注册到 onSubmitEditing 的回调仅在 React-Native 外部测试时有效。有人知道解释吗??
谢谢!!
尝试
if (json.status === "OK") {
console.log(json.results[0].formatted_address)
}
我进行了一些挖掘,发现返回的 JSON 具有状态 属性 和一个结果数组。您可以使用 results[0]
.