代码之家  ›  专栏  ›  技术社区  ›  manAbl

基于状态的函数执行无法正常工作

  •  0
  • manAbl  · 技术社区  · 7 年前

    我想将温度从摄氏度更改为华氏度(反之亦然),但我还没有找到解决这个问题的正确方法,我编写了一个函数,可以进行摄氏度到华氏度的转换,但它给我带来了一个错误。所以我需要有人能够打开我的大脑,并向我解释这一点哈哈(让我明白我在说什么)。

    这是我的代码: https://codepen.io/manAbl/pen/aGymRg?editors=0011

    我在注释中输入了以下函数,这是一个不起作用的函数:

    convertingTemperature() {
    const { Fahrenheit, Celcius } = this.state;
    
    this.setState({
      Fahrenheit: true,
    });
    
    const _Celcius = this.state.weather.weather && this.state.weather.main.temp;
    
    const _Fahrenheit = Math.round(_Celcius * 5 / 9 + 32);
    
    if(Fahrenheit) {
      this.setState({ temp: _Fahrenheit })
    };
    

    }

    我想做的是保持我的状态为布尔值,所以如果华氏度为真,我可以进行转换并调用我的函数,但我认为不起作用的原因是因为我正在从我的天气状态对象中提取值,该值来自我的api调用。所以我想把这个值拉出来,放到一个单独的状态,这样我就可以用它进行转换。

    ---我想说的是,当点击温度时,我希望能够在华氏度和摄氏度之间切换

    1 回复  |  直到 7 年前
        1
  •  2
  •   Thomas Darvik    7 年前

    我更新了您的代码以使用2个组件,其中温度以及与温度相关的所有内容都在 WeatherData 组成部分温度通过道具传递给它,并且始终通过 塞尔修斯 (注意!!!)

    My CodePen

    这里的主要思想是有两个组件,其中温度作为 prop 到另一个组件。该组件还处理从C到F的转换,当用户单击span时,还使用函数将C转换为F getCorrectTemp() (它还将其格式化为字符串。

    注意:记住 bind onClick 事件,否则 this 上下文丢失。

    class WeatherData extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = { isCelcius: true }
      }
    
      toggleIsCelcius() {
        this.setState({isCelcius: !this.state.isCelcius});
      }
    
      getCorrectTemp(temp, isCelcius) {
        if(this.state.isCelcius) return `${this.props.tempCelcius} C`;
        return `${(this.props.tempCelcius*9/5)+32} F`;
      }
    
      render() {
        const { main,name,icon,country,tempCelcius } = this.props;
        if(tempCelcius) {
          const tempFormatted = this.getCorrectTemp(tempCelcius, this.state.isCelcius);
          return (
            <div className='app-wrapper'>
              <p>{name},{country}</p>
              <small>{main}</small>
              <span onClick={this.toggleIsCelcius.bind(this)}>{tempFormatted}</span>
              <img src={icon} alt=''/>
            </div>
          );
        } else {
          return <div className='app-wrapper'>Loading ...</div>
        }
      }
    }
    

    我还添加了一个加载状态,但如果不需要,可以将其删除。只需记住处理尚未从服务器接收到temp的状态。