繁体   English   中英

如何使用来自 API 的天气数据在反应中切换将华氏温度转换为摄氏温度?

[英]how can I toggle convert Fahrenheit to Celsius using weather data from an API in react?

我从 API (openweathermap.org) 获取天气数据我已经将我从 API 获得的所有数据存储在名为“weatherData”的 useState 中,并有条件地在下面的 jsx 中呈现数据。 现在我正在尝试将我从 API 获得的温度从华氏温度转换为摄氏温度并返回,到目前为止,我已经创建了一个 function 尝试执行此操作 每次用户单击按钮时都会启动转换过程. 我将天气数据从华氏温度正确转换为摄氏温度,但我不知道如何将新值显示到下面的 jsx 中。 我怎样才能做到这一点?

function WeatherApp(){
//my useStates
    const [searchBar, setSearchBar] = useState('');
    const [weatherData, setWeatherData] = useState();
    const [currentTempUnit, setCurrentTempUnit] = useState('Farenheit');
    const [buttonText, setButtonText] = useState('C');

//function that get the search bar value when the user type something in
    function getSearchBarValue(e){
        setSearchBar(e.target.value.trim());
    }

//  a function that I am currently working that toggle convert the temperature units from Farenheit to Celcius and back.
//  I've got it to console log the correct value, but I have no clue how display the changed value on the page.
//  where you see "<span>{Math.round(weatherData.main.temp)}</span>" the conditionaly rendered jsx below. 
    function convertTemperature(){
        let tempUnit;
        
        if(currentTempUnit === 'Farenheit'){
            setCurrentTempUnit('Celcius');
            tempUnit = ( Math.round(weatherData.main.temp) - 32)/1.8;
            //setWeatherData(tempUnit)
            setButtonText('F');
        }else{
            setCurrentTempUnit('Farenheit');
            setButtonText('C');
        }

        console.log(tempUnit)
    }

//an async function that calls for weather data from an API. get the data then store that data in the weatherData useState to be used later. 
    async function getWeatherFromAPI(e){
        e.preventDefault();
        const apiKey = 'fd7019c29121761f9602268492840876';
        try{
            const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${searchBar}&&units=imperial&appid=${apiKey}`, {mode: 'cors'})
            const storeWeatherData = await response.json();
            setWeatherData(storeWeatherData);
            console.log(storeWeatherData);
            
        }catch(err){
            err=alert("Im sorry we couldn't get you weather data")
        }
    }
    return(
        <>
            <div className="search-container">
                <form>
                    {/* The search bar  */}
                    <input type="search" placeholder="Enter City Here" className="search-bar"  onChange={getSearchBarValue}/>
                    {/* submit button that gets the data from the API */}
                    <button type="submit" className="search-btn"><FcSearch onClick={getWeatherFromAPI}/></button>
                </form>
            </div>
            <div className="weather-container">
                {/*  conditional rendering the useState weatherdata when asked for and found  */}
                {weatherData && 
                <div className="weather-content-container">

                    <section className="seaction-1">
                        <span>{weatherData.name}</span>
                        <span>{weatherData.sys.country}</span>
                        <img src={`https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/${weatherData.weather[0]["icon"]}.svg`} />
                        {/* this is where I want to change values from F to C and back */}
                        <span>{Math.round(weatherData.main.temp)}</span>
                        <span>{Math.round(weatherData.main.temp_max)}</span>
                        <span>{Math.round(weatherData.main.temp_min)}</span>
                        {/* this is the button that triggers the temperature conversions */}
                        <button onClick={convertTemperature}>{buttonText}</button>
                    </section>

                    <section className="seaction-2">
                        <span>{weatherData.weather[0].description}</span>
                        <span>{weatherData.weather[0].main}</span>   
                    </section>

                    <section className="seaction-3">
                    <img src={humidityImgae} alt="humidity Icon"/>
                    <span>{weatherData.main.humidity}</span>
                    </section>
                </div>
                }

            </div>
        </>
    )
}

我使用烧录数据,因为此时我没有 API

华氏到摄氏度 Function

import { useState, useCallback } from "react";

export default function App() {
  const [currentTempUnit, setCurrentTempUnit] = useState("Farenheit");
  const [buttonText, setButtonText] = useState("F");
  const [weatherData, setWeatherData] = useState(20); // initial Temp F

  const toggleFToC = useCallback(() => {
    let tempUnit;
    if (currentTempUnit === "Farenheit") {
      setCurrentTempUnit("Celcius");
      tempUnit = ((weatherData - 32) * 5) / 9;
      setWeatherData(tempUnit);
      setButtonText("C");
    } else {
      setCurrentTempUnit("Farenheit");
      setButtonText("F");
    }
    console.log(tempUnit);
  }, [weatherData]);

  return (
    <div className="App">
      <div>
        {buttonText} {weatherData}
      </div>
      <button onClick={() => toggleFToC()}>Toggle F to C</button>
    </div>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM