简体   繁体   English

Function 组件在我更改 state 时重新渲染

[英]Function components re-render when I change the state

In this component I'm trying to toggle between Celsius to Fahrenheit.在这个组件中,我试图在摄氏温度和华氏温度之间切换。 I have two functions that do that and save in to the state.我有两个函数可以做到这一点并保存到 state 中。 When I click at onToggleToFahrenheit the function executes and does the job properly, but when I click at onToggleToCelsius , the component rendered and the state reset.当我单击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>
  );
};

This is in the console这是在控制台中在此处输入图像描述

Both the onToggleToFahrenheit and onToggleToCelsius functions enqueue a state update and will trigger a rerender. onToggleToFahrenheitonToggleToCelsius函数都将 state 更新排入队列,并将触发重新渲染。 State isn't resetting, it is being updated. State 没有重置,它正在更新。

I don't see any overt issues with the code other than that it isn't rendering the local state, ie <h1 id="temperature">{data.main.temp}</h1> instead of <h1 id="temperature">{currWeatherFormat.currTemp}</h1> , and also that it is considered anti-pattern to store derived state like a computed conversion from Fahrenheit to Celsius, and back, based on a toggle.除了没有渲染本地 state 之外,我没有看到代码有任何明显的问题,即<h1 id="temperature">{data.main.temp}</h1>而不是<h1 id="temperature">{currWeatherFormat.currTemp}</h1> ,并且还认为存储派生的 state 被视为反模式,例如基于切换的从华氏到摄氏的计算转换,然后返回。 In other words, the state should be what unit you want to display the temp in and do the conversion on the fly when rendering.换句话说,state 应该是您想要显示温度并在渲染时即时进行转换的单位。

Instead of converting and storing the temp locally, use a state to indicate what unit to render the temp as.不要在本地转换和存储温度,而是使用 state 来指示将温度渲染为什么单位。

Example:例子:

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 } }} />

在此处输入图像描述 在此处输入图像描述

编辑功能组件-重新渲染-when-i-change-the-state-im-use-react-hooks

Changes to state will cause your component to re-render - you are doing this in both of your onToggle methods by calling setcurrWeatherFormat with a new value.对 state 的更改将导致您的组件重新渲染 - 您正在通过使用新值调用 setcurrWeatherFormat 在您的两个 onToggle 方法中执行此操作。

I think the issue here is that you are always displaying the temperature using the components prop value and not the state value that you modify.我认为这里的问题是您始终使用 components 属性值而不是您修改的 state 值显示温度。 Try changing尝试改变

<h1 id="temperature">{data.main.temp}</h1>

To

<h1 id="temperature">{currWeatherFormat.currTemp}</h1>

Additionally, what is the data.main.temp being passed to the component?此外,传递给组件的 data.main.temp 是什么? Is this a celsius or fahrenheit value or something else?这是摄氏或华氏值还是其他值? You may not need to do one of the conversions...您可能不需要进行其中一项转换...

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

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