You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件调用天气API报Cannot read property 'state' of undefined如何解决

报错根本原因

你将React原生生命周期方法componentDidMount直接作为按钮的点击回调,该方法没有提前绑定组件实例的this指向,触发时内部的this为undefined,因此读取this.state就抛出了对应错误。
同时你的代码还存在两处可优化的问题:

  • input的value属性错误绑定为this.state.value,实际应该对应this.state.cityName
  • 不建议直接复用生命周期方法处理业务逻辑,单独封装请求方法更符合开发规范

修复方案

方案1(推荐):单独封装天气请求方法并绑定this

修改后的完整代码如下:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cityName: "",
      weather: ""
    }
    this.handleChange = this.handleChange.bind(this);
    // 绑定自定义请求方法的this指向
    this.fetchWeather = this.fetchWeather.bind(this);
  }

  // 单独封装天气请求逻辑
  fetchWeather() {
    fetch(`https://api.weatherapi.com/v1/current.json?key=.....&q=${this.state.cityName}&aqi=no`)
      .then(response => response.json())
      .then(json => {
        this.setState({ weather: json});
      });
  }

  componentDidMount() {
    // 如果需要页面初始化时请求可以在这里调用this.fetchWeather,不需要就留空
  }

  handleChange(event) {
    this.setState({cityName: event.target.value});
  }

  render() {
    return (
      <center>
        <p><font color="bluesky" size="10">Weather</font></p>
        <div class="card-body">
          {/* 修正input的value绑定 */}
          <input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Type the name of city"></input>
          <h3>{this.state.cityName}</h3>
        </div>
        <div>
          {/* 点击事件绑定到自定义方法 */}
          <button className="btn btn-secondary btn-sm" onClick={this.fetchWeather}>Check weather</button>
        </div>
      </center>
    );
  }
}

方案2(临时快速修复):用箭头函数绑定this

如果你不想调整代码结构,也可以直接在点击事件处用箭头函数绑定this指向,不需要修改其他代码:

<button className="btn btn-secondary btn-sm" onClick={() => this.componentDidMount()}>Check weather</button>

该方案仅适合快速验证逻辑,生产环境更推荐方案1的写法,逻辑拆分更清晰。

内容的提问来源于stack exchange,提问作者anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 09:24:11