gpt4 book ai didi

javascript - react : Cannot read property 'getWeather' of undefined

转载 作者:行者123 更新时间:2023-11-30 11:29:51 25 4
gpt4 key购买 nike

我试图弄清楚这种类型错误是从哪里来的,但我似乎无法查明它。也许我错过了 React 的一个重要概念。

我在 React 中有一个天气类:

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

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

最佳答案

您需要同时绑定(bind)getWeatherhandleSubmit:

  constructor(props) {
super(props);

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

this.getWeather = this.getWeather.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

关于javascript - react : Cannot read property 'getWeather' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46655003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com