【问题标题】:Conditional statement inside render producing error渲染中的条件语句产生错误
【发布时间】:2017-04-24 21:10:21
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs jsx


    【解决方案1】:

    您缺少上下文。

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

    【讨论】:

    • 你是个救命恩人!
    猜你喜欢
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2020-10-09
    • 2020-06-13
    • 2012-09-01
    • 2019-03-08
    • 1970-01-01
    相关资源
    最近更新 更多