【问题标题】:Selecting Specific information from an API and console log that information in ReactNative从 API 和控制台中选择特定信息并在 React Native 中记录该信息
【发布时间】: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


【解决方案1】:

你应该使用setparkingPostcode(response2.data.result)

【讨论】:

    【解决方案2】:
    1. 您确定console.log(response2.data) 记录了正确的输出吗?

    2. searchPostcode 是一个异步函数,这意味着您不知道该函数何时完成执行并更新您的状态。

    这意味着这段代码

    {parkingPostcode.map((val, index) => {
        key={index}
        console.log(val.postcode) 
    })}
    

    searchPostcode 完成之前执行,因此您没有任何结果。

    1. 这段代码

      {parkingPostcode.map((val, index) => {
           key={index}
           console.log(val.postcode) 
      })}
      

    应该循环遍历一个数组,并为每个元素返回一些东西,它没有返回,它只是给出一个名为 key 的变量(一个未在代码中任何地方定义的变量)一个值 @987654328 @ 然后它什么都不返回。

    无论如何,这应该不会失败,因为parkingPostcode 被初始化为一个空数组,所以循环一个空数组应该不会失败。

    根据您的错误,API 调用很可能会失败,并且您没有 catch 块来处理失败的情况,因此将所有与 API 调用相关的代码包装在 try-catch 中应该可以消除错误。

    您必须修复其余代码才能处理这种情况。

    【讨论】:

    • 所以你的意思是函数不应该是异步的?是的,我确定 response2.data 记录了正确的输出
    • 还有一些我现在才注意到的东西。您的 searchPostcode 函数实际上在哪里被调用?从您的代码中,该函数永远不会被调用。
    • 这是 api 搜索有效的证明:prnt.sc/r08xyy
    • 根据您的屏幕截图,您有一个result 对象。 postcoderesult 对象内。我从来没有看到你访问过result.postcode
    • 抱歉,我只是在学习这种新的编程语言。您能告诉我如何访问 result.postcode 以及在哪里访问它吗?
    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 2015-12-18
    • 1970-01-01
    • 2014-05-25
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多