开发者问题收集

React:无法读取未定义的属性“getWeather”

2017-10-09
310

我试图找出这种类型错误的来源,但似乎无法准确定位。也许我遗漏了 React 的一个重要概念。

我在 React 中有一个 Weather 类,如下所示:

class Weather extends Component {
  constructor(props) {
    super(props);

    this.state = {
      cityName: "San Francisco",
      temp: null,
    }
  }

  getWeather(city) {
    // does fetch request to openweathermap.org
  }

  handleSubmit(event) {
    event.preventDefault();
    this.getWeather(this.state.cityName);
    // this.state.cityName is updated as the user types
  }
}

问题是,每当我单击提交按钮时,我都会收到有关 getWeather 函数的错误,提示:

TypeError: Cannot read property 'getWeather' of undefined

有什么建议吗?我尝试绑定 getWeather 函数,但没有帮助。

2个回答

您需要绑定 getWeatherhandleSubmit

  constructor(props) {
    super(props);

    this.state = {
      cityName: "San Francisco",
      temp: null,
    }

    this.getWeather = this.getWeather.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
Daniel
2017-10-09

在您的情况下, this 与元素相关,而不是类。使用箭头函数。

handleSubmit = (event) => {
    event.preventDefault();
    this.getWeather(this.state.cityName);
    // this.state.cityName is updated as the user types
  }
Georgy
2017-10-09