首页 > 解决方案 > 无法读取 API 调用中未定义的属性“状态”

问题描述

我在反应中有以下组件

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cityName: "",
      weather: ""
    }
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    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});
      });
  }

  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 type="text" value={this.state.value} 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.componentDidMount}>Check weather</button>
        </div>
      </center>
    );
  }
}

对于这行代码, fetch(`https://api.weatherapi.com/v1/current.json?key=...&q=${this.state.cityName}&aqi=no`)
我得到下一个错误“TypeError:无法读取未定义的属性'状态'”。我是新手,有人可以帮我解决这个错误吗?

标签: reactjs

解决方案


您正在调用组件生命周期方法来处理表单提交。就像您拥有 changeHandler 一样创建一个 submitHandler ,它应该可以正常工作。

onSubmit = () => {
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});
  });
}

该按钮将被配置为:

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

专业提示:使用箭头函数在组件中定义自定义方法。

注意:您需要配置 API 密钥并正确处理响应,在第二个 .then() 中使用 console.log(json) 并查看您得到了什么。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cityName: "",
      weather: ""
    }
  }

  onSubmit = () => {
    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});
      });
  }

  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 type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Type the name of city"></input>
          <h3>{this.state.weather}</h3>
        </div>
        <div>
          <button className="btn btn-secondary btn-sm" onClick={this.onSubmit}>Check weather</button>
        </div>
      </center>
    );
  }
}

推荐阅读