在这个组件中,我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>
  );
};

This is in the console enter image description here

推荐答案

对状态的更改将导致组件重新呈现-您可以在两个on至gger方法中通过使用新值调用setCurWeatherFormat来实现这一点.

我认为这里的问题是,您总是使用组件属性值而不是您修改的状态值来显示温度. 试着换一件

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

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

此外,传递给组件的data.main.temp是什么?这是摄氏度、华氏温度还是其他值?你可能不需要做任何一次转换.

Javascript相关问答推荐

假设我有2个对象,根据它们,我想要新对象

在shiny 模块中实现JavaScript

如何通过继承contentitable属性的元素捕捉keydown事件?

如何让\w token 在此RegEx中表现得不贪婪?

布局样式在刷新时不持续

foreach循环中的Typescript字符串索引

Chart.js V4切换图表中的每个条,同时每个条下有不同的标签.怎么做?

将字符串UTC Date转换为ngx—counting leftTime配置值的数字

Chart.js 4.4.2,当悬停在一个数据点上时,如何在工具提示中拥有多个数据点/标签?

如何将react—flanet map添加到remixjs应用程序

如何在coCos2d-x中更正此错误

对路由DOM嵌套路由作出react

为什么客户端没有收到来自服务器的响应消息?

我想将Sitecore搜索面过滤器从多个转换为单个

如何防止ionic 输入中的特殊字符.?

我想使用GAS和HTML将从Electron 表格中获得的信息插入到文本字段的初始值中

如何使用画布在另一个内部绘制一个较小但相同的形状,同时保持恒定的边界厚度?

如何根据输入数量正确显示alert ?

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

为什么我不能使用其同级元素调用和更新子元素?