試圖返回weatherMsg,它是從對(duì)天氣API 的請(qǐng)求創(chuàng)建的字符串。如控制臺(tái)日志所示,它正確請(qǐng)求天氣。return 是 '' 的初始值。class Weather extends React.Component { render() { let request = require('request'); let apiKey = process.env.REACT_APP_WEATHER_API_KEY; let city = process.env.REACT_APP_WEATHER_CITY; let url = `http://api.openweathermap.org/data/2.5/weather?id=${city}&units=imperial&appid=${apiKey}` let weatherMsg = ''; request(url, function (err, response, body) { if(err){ console.log('error retrieving weather'); } else { let weather = JSON.parse(body); console.log(weather); weatherMsg = "It's {this.state.weather.main.temp} degrees in {this.state.weather.name}."; } }); return( <div>{weatherMsg}</div> ) }}
在請(qǐng)求調(diào)用中設(shè)置變量不會(huì)更新變量(返回值為 ' ')
富國滬深
2021-08-26 16:45:46