渲染中的条件语句产生错误

Conditional statement inside render producing error

我正在尝试为我的天气应用程序创建一个切换按钮,您可以在其中将温度从摄氏度切换到华氏度。

我发现这行代码似乎是导致问题的原因:

<td>{ this.state.celsius ? cTemp : fTemp }</td>

这是控制台错误消息:

Uncaught (in promise) TypeError: Cannot read property 'state' of undefined
    at renderWeather (http://localhost:8080/bundle.js:25076:16)

其余代码供参考:

import React, { Component } from 'react';

export default class WeatherList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      celsius: true
    }

    this.onUnitChange = this.onUnitChange.bind(this);
  }

  renderWeather(cityData) {
    const name = cityData.name;
    const country = cityData.sys.country;
    const cTemp = (cityData.main.temp - 273.15).toFixed(1);
    const fTemp = (cityData.main.temp * 9/5 - 459.67).toFixed(1);

    return (
      <tr key={name}>
        <td>{name}, {country}</td>
        <td>{ this.state.celsius ? cTemp : fTemp }</td>
      </tr>
    )
  }

  onUnitChange() {
    if (this.state.celsius) {
      this.setState({
        celsius: false
      });
    }
    else {
      this.setState({
        celsius: true
      });
    }
  }

  render() {
    return (
      <table className='table table-hover'>
        <thead>
          <tr>
            <th>City</th>
            <th>Temperature °<span className='unit-symbol' onClick={this.onUnitChange}>{ this.state.celsius ? 'C' : 'F' }</span></th>
            <th>Weather</th>
          </tr>
        </thead>
        <tbody>
          {this.props.cities.map(this.renderWeather)}
        </tbody>
      </table>
    )
  }
}

您缺少上下文。

尝试{this.props.cities.map(this.renderWeather.bind(this)}