我正在尝试在React Native中进行fetch 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之外进行测试时才有效。有谁知道解释?
谢谢!
答案 0 :(得分:0)
尝试
if (json.status === "OK") {
console.log(json.results[0].formatted_address)
}
我做了一些挖掘,我看到返回的JSON有一个status属性和一个结果数组。您可以使用results[0]
访问该结果数组中的第一项。