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

标签 javascript reactjs if-statement runtime-error

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

这是我的代码: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 })
};

}

我想要做的是将我的状态保持为 bool 值,因此如果华氏度为真,我可以进行转换并调用我的函数,但我认为不起作用的原因是因为我正在提取该值来 self 的天气状态对象,它来 self 的 api 调用。所以我想将该值提取到一个单独的状态,以便我可以用它进行转换。

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

最佳答案

我更新了您的代码以使用 2 个组件,其中温度以及与温度相关的所有内容都在 WeatherData 组件中定义。温度使用 props 传递给它,并且总是以 Celcius 传递。 (注意!!!)

My CodePen

这里的主要思想是您有两个组件,其中 temp 作为 prop 传递给另一个组件。该组件还处理从 C 到 F 的转换,并且当用户单击范围时,还使用函数 getCorrectTemp() 将 C 转换为 F(该函数还将其格式化为字符串。

注意:记住onClick事件中的bind,否则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>
    }
  }
}

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

关于javascript - 基于状态的函数执行无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201712/

相关文章:

reactjs - Textarea 自动高度在 flex 中不起作用

if-statement - 当for循环内遇到if语句时跳过for循环

c# - 如果其他语句逻辑

python - Python 中的 if 和 else 条件问题

javascript - Reactjs Redux 使用输入更新状态/存储中的数据值

javascript - 如何将焦点设置在 onRowClicked 行中的第一个可编辑单元格上?

JavaScript 如何使用 getDate() 修复获取一个月中的天数?

javascript - 是否可以对 Meteor 用户进行响应式(Reactive) isVerified 调用?

javascript - Underscore.js 为什么要定义函数别名

javascript - 如何实现根据 Redux 上按下的按钮从 API 接收不同数据的按钮?