[英]Function components re-render when I change the state
在这个组件中,我试图在摄氏温度和华氏温度之间切换。 我有两个函数可以做到这一点并保存到 state 中。 当我单击onToggleToFahrenheit
时, function 会执行并正确完成工作,但是当我单击onToggleToCelsius
时,组件会呈现并且 state 会重置。
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>
);
};
onToggleToFahrenheit
和onToggleToCelsius
函数都将 state 更新排入队列,并将触发重新渲染。 State 没有重置,它正在更新。
除了没有渲染本地 state 之外,我没有看到代码有任何明显的问题,即<h1 id="temperature">{data.main.temp}</h1>
而不是<h1 id="temperature">{currWeatherFormat.currTemp}</h1>
,并且还认为存储派生的 state 被视为反模式,例如基于切换的从华氏到摄氏的计算转换,然后返回。 换句话说,state 应该是您想要显示温度并在渲染时即时进行转换的单位。
不要在本地转换和存储温度,而是使用 state 来指示将温度渲染为什么单位。
例子:
const CurrentWeather = ({ data }) => {
const [inCelsius, setInCelsius] = useState(false);
const toggleTempUnit = () => setInCelsius((c) => !c);
const getTemp = (temp) =>
Number(inCelsius ? ((temp - 32) * 5) / 9 : temp).toFixed(2);
return (
<div className="bottom-left">
<h1 id="temperature">
{getTemp(data.main.temp)}°{inCelsius ? "C" : "F"}
</h1>
<button type="button" onClick={toggleTempUnit}>
°F|°C
</button>
</div>
);
};
...
<CurrentWeather data={{ main: { temp: 32.21 } }} />
对 state 的更改将导致您的组件重新渲染 - 您正在通过使用新值调用 setcurrWeatherFormat 在您的两个 onToggle 方法中执行此操作。
我认为这里的问题是您始终使用 components 属性值而不是您修改的 state 值显示温度。 尝试改变
<h1 id="temperature">{data.main.temp}</h1>
至
<h1 id="temperature">{currWeatherFormat.currTemp}</h1>
此外,传递给组件的 data.main.temp 是什么? 这是摄氏或华氏值还是其他值? 您可能不需要进行其中一项转换...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.