内部渲染产生错误的条件语句

时间:2017-04-24 21:10:21

标签: reactjs jsx

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

我发现这行代码似乎导致了这个问题:

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

1 个答案:

答案 0 :(得分:0)

你错过了上下文。

尝试 @echo off title text saver/displayer echo This version saves User Entered text as an "echo" via the "set" command, the "echo" command, and the "type" command. set /p text=Enter text here: echo You have entered: %text%>enteredtext.yourtextfile type enteredtext.yourtextfile pause del enteredtext.yourtextfile exit