在这个组件中,我try 在摄氏度和华氏温度之间切换.我有两个函数可以做到这一点,并保存到国家.当我点击onToggleToFahrenheit
时,函数执行并正确地完成工作,但当我点击onToggleToCelsius
时,组件呈现并且状态重置.
import React, { useState, useEffect } from "react";
export const CurrentWeather = ({ data }) => {
console.log("renderrrr component");
const [currWeatherFormat, setcurrWeatherFormat] = useState({
currTemp: data.main.temp,
});
useEffect(() => {
console.log("aaa", currWeatherFormat);
}, [currWeatherFormat]);
const onToggleToFahrenheit = (celsius) => {
console.log("celsius", celsius);
const fahrenheit = celsius * 1.8 + 32;
setcurrWeatherFormat({ ...currWeatherFormat, currTemp: fahrenheit });
};
const onToggleToCelsius = (fahrenheit) => {
console.log("fehrenheit", fahrenheit);
const celsius = ((fahrenheit - 32) * 5) / 9;
setcurrWeatherFormat({ ...currWeatherFormat, currTemp: celsius });
};
return (
<div className="bottom-left">
<h1 id="temperature">{data.main.temp}</h1>
<h2
onClick={() => onToggleToCelsius(data.main.temp)}
id="celsius"
>
°C
</h2>
<h2 id="temp-divider">/</h2>
<h2
onClick={() => onToggleToFahrenheit(data.main.temp)}
id="fahrenheit"
>
°F
</h2>
</div>
);
};