首页 > 解决方案 > ReactJS 渲染问题获取 API

问题描述

我正在尝试使用 Geolocation 获取 WeatherApp API。我的问题是渲染:它不允许我在获取之前渲染页面(但是在我设法获取之后,代码似乎可以工作)。

返回错误信息:

Type Error : Cannot Read Property 'temp' of undefined
import React, { useState } from 'react';
import './App.css';
import Axios from 'axios';

function App() {

  const [ positionLat, setPositionLat ] = useState('') ;
  const [ positionLong, setPositionLong] = useState('') ;
  
  navigator.geolocation.getCurrentPosition(function(position) {
    setPositionLat(position.coords.latitude);
    setPositionLong(position.coords.longitude);
  });

  const [weather, setWeather] = useState('');

  const fetchingWeather = () => {
    Axios.get(
      `https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
    .then((res) => {
      console.log(res.data.main.temp)
      setWeather(res.data)
    })
  }

// this line is returning the error 
 console.log(weather.main.temp)

  return (
    <div className="App">
      <p>lattitude :{positionLat}</p>
      <p>longitude :{positionLong}</p>
      <button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
    </div>
  );
}

export default App;

标签: javascriptreactjs

解决方案


获取天气和设置天气状态是异步的,您是weather.main.temp在请求完成之前进行控制台日志记录。获取数据是 reactjs 的副作用。所以建议你通过使用useEffect钩子来获取天气信息并在那里设置天气状态。

import React, { useState, useEffect } from 'react';
import './App.css';
import Axios from 'axios';

function App() {

  const [ positionLat, setPositionLat ] = useState('') ;
  const [ positionLong, setPositionLong] = useState('') ;
  
  navigator.geolocation.getCurrentPosition(function(position) {
    setPositionLat(position.coords.latitude);
    setPositionLong(position.coords.longitude);
  });

  const [weather, setWeather] = useState('');

  const fetchingWeather = () => {
    Axios.get(
      `https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
    .then((res) => {
      console.log(res.data.main.temp)
      setWeather(res.data)
    })
  }


  useEffect(() => {
    fetchingWeather();
  }, [weather])

  return (
    <div className="App">
      <p>lattitude :{positionLat}</p>
      <p>longitude :{positionLong}</p>
      <button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
    </div>
  );
}

export default App;

那应该行得通。


推荐阅读