Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应:无法读取属性';getWeather';未定义的_Javascript_Reactjs - Fatal编程技术网

Javascript 反应:无法读取属性';getWeather';未定义的

Javascript 反应:无法读取属性';getWeather';未定义的,javascript,reactjs,Javascript,Reactjs,我试图找出这种类型的错误是从哪里来的,但我似乎无法准确指出它。也许我遗漏了一个重要的反应概念 我在伦敦上了一堂天气课,比如: class Weather extends Component { constructor(props) { super(props); this.state = { cityName: "San Francisco", temp: null, } } getWeather(city) { // do

我试图找出这种类型的错误是从哪里来的,但我似乎无法准确指出它。也许我遗漏了一个重要的反应概念

我在伦敦上了一堂天气课,比如:

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
  }
}
问题是,每当我单击submit按钮时,我都会收到一个关于getWeather函数的错误,上面说:

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


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

您需要同时绑定
getWeather
handleSubmit

  constructor(props) {
    super(props);

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

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

在您的例子中,
这个
与元素相关,而不是类。使用箭头功能

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

可能是handleSubmit未绑定的问题。你能告诉我们在哪里使用handleSubmit吗?@NicholasTower正是这样。下面的丹尼尔帮我搞定了。我不确定我是怎么漏掉的,但正如我在下面所说的,我的组件比我的示例显示的要大得多,所以我想“很容易”被忽略。就是这样。我不知道我怎么会忘了也要绑手信。这个组件比我用这个代码设计的要大,所以我完全忽略了这一点。我有一种感觉,基于这个错误,绑定被断开了,而你马上就发现了。非常感谢。