-1

这是我为 axios 调用 API 的代码,我必须将它迁移到 fetch() 函数:

  handleClick = e => {
    axios
      .post(
        "https://api.openweathermap.org/data/2.5/weather?q=" +
          this.state.term +
          "&units=metric&appid=" +
          API_KEY
      )
      .then(res => {
        this.setState({
          city_name: res.data.name,
          temp: res.data.main.temp,
          humidty: res.data.main.humidity,
          wind: res.data.wind.speed,
          weather_status: res.data.weather[0].main,
          weather_desc: res.data.weather[0].description,
          weather_icon: res.data.weather[0].icon
        });
      })//error logging
      .catch(error => {
        console.log(error);
      });
  };

  render() {
    return (
      <div className="container">
        <h1 className="header">Task 14 - Level 2</h1>
        <Form onChange={this.handleChange} onClick={this.handleClick} />
        <WeatherApp data={this.state} />
        <div className="img"></div>
      </div>
    );
  }
}

如何将 axios 调用更改为 fetch() 函数?

4

1 回答 1

-1

这是 fetch 中的等价物。

const handleClick = () => {

   fetch( "https://api.openweathermap.org/data/2.5/weather?q=" +
          this.state.term +
          "&units=metric&appid=" +
          API_KEY,{ method: 'POST' }). then( res => res.json())
          .then( res => {
   this.setState({
          city_name: res.data.name,
          temp: res.data.main.temp,
          humidty: res.data.main.humidity,
          wind: res.data.wind.speed,
          weather_status: res.data.weather[0].main,
          weather_desc: res.data.weather[0].description,
          weather_icon: res.data.weather[0].icon
        });

})
}
于 2022-01-26T09:25:02.197 回答