【发布时间】:2020-02-10 14:15:32
【问题描述】:
我目前正在 reactNative 中工作,并且根据用户的位置(纬度和经度),我正在尝试查找该给定位置周围的邮政编码。使用 API,我可以轻松地转换邮政编码并返回包含不同对象的 json 响应,每个对象对应一个邮政编码。从该信息中,我只想提取“邮政编码”字段。这是我到目前为止所做的,但我遇到了错误:
const [parkingPostcode,setparkingPostode] = useState([])
//In here I store the information
const searchPostcode = async() => {
const response2 = await postcodes.get("",{
params:{
longitude: userLongitude,
latitude : userLatitude,
limit: 10
}
})
console.log(response2.data)
setparkingPostode(response2.data)
// This is where I make the API call and everything works as expected
}
//Below is the function I want to use to display the postcodes which are around the user:
{parkingPostcode.map((val, index) => {
key={index}
console.log(val.postcode)
})}
当我尝试运行它时,我收到以下错误: "[未处理的承诺拒绝:TypeError: undefined is not a function (near '...parkingPostcode.map...')]"
这是完整的代码
import React ,{Component,useState,useEffect} from 'react'
import {View,Text,StyleSheet,Dimensions,Button,Alert,FlatList,TouchableOpacity} from 'react-native'
import MapView , {Marker}from 'react-native-maps'
import axios from 'axios'
import { TextInput } from 'react-native-gesture-handler'
import camdenParking from '../api/camdenParking'
import postcodes from '../api/postcodes'
import SearchBar from '../components/SearchBar'
const HomeScreen = ({navigation})=>
{
const [parkingSpaces,setparkingSpaces] = useState([])
const [parkingPostcode,setparkingPostcode] = useState([])
const[term,setTerm] = useState('')
let userLatitude = 0
let userLongitude = 0
const searchApi = async() => {
const response = await camdenParking.get("",{
params:{
postcode: term
}
}) // you can change this later on
console.log(response.data)
setparkingSpaces(response.data)
console.log(term)
}
const searchPostcode = async() => {
const response2 = await postcodes.get("",{
params:{
longitude: userLongitude,
latitude : userLatitude,
limit: 10
}
}) // you can change this later on
console.log(response2.data)
setparkingPostcode(response2.data)
}
const showPostcode =() => {
{parkingPostcode && parkingPostcode.map((val, index) => {
key={index}
console.log(val.postcode)
})}
}
const findCoordinates = () => {
navigator.geolocation.getCurrentPosition(
position => {
const locationString = JSON.stringify(position); // Here we get the JSON object but it needs to be parsed
var longLat = JSON.parse(locationString); // Here we parse the JSON object
userLatitude=longLat.coords.latitude
userLongitude=longLat.coords.longitude
console.log(userLatitude) // This prints the current latitude from the user
console.log(userLongitude) // This prints the longitude
},
error => Alert.alert(error.message),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
);
};
return(
<View style={styles.container}>
<SearchBar
term={term}
onTermChange={newTerm=>setTerm(newTerm)}
onTermSubmit={()=> searchApi(term)}
/>
<MapView
style={styles.mapStyle}
initialRegion={{
latitude: 51.539190,
longitude: -0.142500,
latitudeDelta: 0.0122,
longitudeDelta: 0.0421,
}}
>
{parkingSpaces.map((val, index) => {
return (<MapView.Marker
coordinate={{
latitude: parseFloat(val.latitude),
longitude:parseFloat(val.longitude)
}}
key={index}
>
<MapView.Callout tooltip style={styles.customView}>
<View style={styles.ParkingPopUpStyle}>
<Text style = {styles.parkingPopUpText}>
Restrictions: {val.restriction_type}{"\n"}{"\n"}
Maximum Stay: {val.maximum_stay}{"\n"}{"\n"}
Tariff : {val.tariff}{"\n"}{"\n"}
Operating Hours: {val.times_of_operation}{"\n"}{"\n"}
Nearest Pay Machine: {val.nearest_machine}{"\n"}{"\n"}
Parking Bay Length: {val.parking_bay_length_metres} {'Metres'}{"\n"}{"\n"}
Parking Permit Required To Park For Free: {val.controlled_parking_zone}{"\n"}{"\n"}
</Text>
</View>
</MapView.Callout>
</MapView.Marker>
);
})}
</MapView>
<Button style={{ borderWidth: 2, alignItems:'right',justifyContent:'right'}} title="Info" onPress={() => console.log("This is not fired")}/>
<Button onPress={searchApi} title=" Click Here To Get Parking Spaces" />
<Button onPress={findCoordinates} title=" Click Here To Get User's Location" />
<Button onPress={searchPostcode} title=" Click Here To Get Near Postcodes" />
<Button onPress={showPostcode} title=" Display Postcode" />
<Text style={styles.bottomText}>{parkingSpaces.length} Parking Spaces found around {term}</Text>
<Text>
NW6 5HZ {"\n"}
NW1 0XF {"\n"}
NW1 1QE {"\n"}
NW6 1NB {"\n"}
</Text>
</View>
);
};
const styles = StyleSheet.create(
{
container:{
flex:1,
backgroundColor: '#fff',
//alignItems: 'center',
//justifyContent: 'center',
//...StyleSheet.absoluteFillObject,
//marginLeft:0,
//height:400,
//width:400,
//justifyContent:"flex-end",
//alignItems:"center",
},
mapStyle: {
width: 400,
height:400,
//width: Dimensions.get('window').width,
//height: Dimensions.get('window').height,
},
ParkingPopUpStyle:{
backgroundColor:'#CECECE',
borderWidth:0, //1
width: 375,
height:300,
flexDirection:'row',
justifyContent:'space-between'
},
bottomText:{
textAlign:'center'
},
parkingPopUpText:{
fontSize: 16,
marginLeft:10,
marginTop:7,
}
}
)
export default HomeScreen
【问题讨论】:
-
您希望
parkingPostcode是一个数组。你确定response2.data是一个数组吗? -
是的,这是 response2.data:prnt.sc/r08xyy
-
对我来说似乎是一个字符串。发生此错误是因为
parkingPostcode没有响应方法map。你能告诉我console.log(response2.data.constructor.name)的产量吗? -
这是它产生的:对象
标签: json reactjs api react-native