2017-04-24 35 views
0

我想为我的天气应用程序创建一个切换按钮,在那里你可以将温度从摄氏温度切换到华氏温度。渲染产生错误的条件声明

我已经确定,这行代码似乎是造成问题的原因:

<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> 
    ) 
    } 
} 

回答

0

您错过了上下文。

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

+0

人你是一个生命的救星! – doctopus