代码之家  ›  专栏  ›  技术社区  ›  Hadi Zouhbi

为什么我首先在控制台中得到Null,然后再得到值(react.js)

  •  1
  • Hadi Zouhbi  · 技术社区  · 4 年前

    应该得到纬度和经度的值,但由于某种原因,我得到的初始状态是“null”,然后在同一时间得到另一个控制台中的数据响应。

    This is what the console.log looks like when I refresh the page

    如图所示,它首先返回null,然后(不刷新或任何操作)返回值。

    这就是我获得coords值的地方(从react库)

    //Getting geolocation
    const {coords, isGeolocationAvailable , isGeolocationEnabled} = useGeolocated({
        positionOptions: {
            enableHighAccuracy: false
        },
        userDecisionTimeout: 5000,
    })
    
    //Setting Latitude and Longitude states
    useEffect (() => {
        if (coords) {
           setLatitiude(coords.latitude)
           setLongitude(coords.longitude) 
        }
    }, [coords]);
    
    //Fetch data from API
    useEffect (() => {
        console.log(`Latitude = ${latitude} and Longitude = ${longitude}`)
        //Function to call API
        const weatherForecast = async () => {
            await axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
            .then((res) => {
            setWeatherDetails(res.data)
        })
        } 
    
        if(latitude !== null & longitude !== null) {
            weatherForecast()
        } else {
            console.log("Error getting data")
        }
       
     }, [latitude , longitude]);
    

    3 回复  |  直到 4 年前
        1
  •  2
  •   Sanket Shah    4 年前

    null 因为您在 coords 甚至加载了数据。

    试试这个

    //Getting geolocation
    const {coords, isGeolocationAvailable , isGeolocationEnabled} = useGeolocated({
        positionOptions: {
            enableHighAccuracy: false
        },
        userDecisionTimeout: 5000,
    })
    
    //Setting Latitude and Longitude states
    useEffect (() => {
        if (coords) {
           setLatitiude(coords.latitude)
           setLongitude(coords.longitude) 
        }
    }, [coords]);
    
    //Function to call API
    const weatherForecast = async () => {
       await axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
         .then((res) => {
           setWeatherDetails(res.data)
         }).catch(() => {
           console.log("Error getting data")
         })
    } 
    
    //Fetch data from API
    useEffect (() => {
        if(latitude !== null && longitude !== null){ 
         console.log(`Latitude = ${latitude} and Longitude = ${longitude}`)
            weatherForecast()
        }
       
     }, [latitude , longitude]);
    
        2
  •  1
  •   Erik    4 年前

    第二次,我猜cords存在,并设置long和lat。这会触发重新渲染,因为第二次useEffect在其依赖关系中有它们。大堆

    在react中,多次重新渲染非常常见。

        3
  •  0
  •   Dorji Tshering    4 年前