React中使用Axios调用OpenWeather API无法传入cityid参数怎么解决?
你报错的核心原因是普通字符串中无法直接解析JS变量,你写的"https://xxx?id={this.props.cityid}"里的{this.props.cityid}会被当成普通字符串拼接在URL里,而不是被替换成实际的城市ID值,所以服务器收到无效的ID参数返回400错误。
解决方法
1. 正确拼接URL参数
有两种常用写法实现变量拼接:
方法1:使用ES6模板字符串(推荐)
用反引号`包裹URL,变量用${}包裹即可自动解析:
axios.get(`https://api.openweathermap.org/data/2.5/forecast?id=${this.props.cityid}&units=metric&appid=b606f9db39d148829c9500a2651c63dd`)
注意这里替换成了forecast接口,因为你代码逻辑里用了response.data.list[0]获取数据,这个字段只有多日预报的forecast接口才有,你之前写的weather是实时天气接口,返回值里没有list字段,就算参数拼对也会报错。
方法2:使用字符串拼接
用加号把字符串和变量拼接起来:
axios.get("https://api.openweathermap.org/data/2.5/forecast?id=" + this.props.cityid + "&units=metric&appid=b606f9db39d148829c9500a2651c63dd")
2. 补充适配逻辑,避免切换城市不刷新数据
现在你的请求只在componentDidMount触发,也就是Day1组件第一次加载的时候才会发请求,如果用户切换城市,Day1组件没有重新挂载的话不会刷新数据,建议补充componentDidUpdate生命周期监听cityid变化,同时加非空判断避免初始空ID发无效请求,另外你之前降水的赋值逻辑有误,把最高温赋值给了降水,也同步修正。
修改后的完整Day1.js代码如下:
import React, { Component } from "react"; import { WiDayCloudy } from "weather-icons-react"; import classes from "./City.module.css"; import axios from "axios"; class Day1 extends Component { state = { DateAndTime: null, MaxTemp: null, MinTemp: null, Humidity: null, Precipitation: null, loading: false, }; // 封装请求方法复用 fetchWeather = (cityid) => { if (!cityid) return; // ID为空直接返回,不发无效请求 this.setState({ loading: true }); axios .get( `https://api.openweathermap.org/data/2.5/forecast?id=${cityid}&units=metric&appid=b606f9db39d148829c9500a2651c63dd` ) .then((response) => { this.setState({ DateAndTime: response.data.list[0].dt_txt, MaxTemp: response.data.list[0].main.temp_max, MinTemp: response.data.list[0].main.temp_min, Humidity: response.data.list[0].main.humidity, Precipitation: response.data.list[0].rain ? (response.data.list[0].rain['3h'] || '0mm') : "none", loading: false }); }) .catch((error) => { console.log(error); this.setState({ loading: false }); }); } componentDidMount() { this.fetchWeather(this.props.cityid); } // 监听cityid变化,切换城市后自动重新请求 componentDidUpdate(prevProps) { if (prevProps.cityid !== this.props.cityid) { this.fetchWeather(this.props.cityid); } } render() { if (this.state.loading || !this.state.DateAndTime) { return ( <div className={classes.City}> <h1>加载中...</h1> <h4>最高温度=加载中...</h4> <h4>最低温度=加载中...</h4> <h4>湿度=加载中...</h4> <h4>降水=加载中...</h4> </div> ); } return ( <div className={classes.City}> <WiDayCloudy size={100} color="rgb(156, 231, 231)" /> <h1>第一天 {this.state.DateAndTime}</h1> <h4>最高温度={this.state.MaxTemp}°C</h4> <h4>最低温度={this.state.MinTemp}°C</h4> <h4>湿度={this.state.Humidity}%</h4> <h4>降水={this.state.Precipitation}</h4> </div> ); } } export default Day1;
内容的提问来源于stack exchange,提问作者ARPIT PRASAD
相关产品推荐
相关产品推荐

