簡體   English   中英

Function 組件在我更改 state 時重新渲染

[英]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>
  );
};

這是在控制台中在此處輸入圖像描述

onToggleToFahrenheitonToggleToCelsius函數都將 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 } }} />

在此處輸入圖像描述 在此處輸入圖像描述

編輯功能組件-重新渲染-when-i-change-the-state-im-use-react-hooks

對 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM