我正在尝试编写一个 preact 脚本,该脚本将根据获取的 API 数据显示不同的图像。但是,即使我使用了 componentWillUpdate() 函数,在渲染输出之前似乎也没有调用 fetchWeatherData() 函数。当我在返回数据之前尝试在 render() 函数中打印 this.state.locate 时,输出总是未定义的,但是我需要这个变量来操作我想要显示的图像。谢谢你的帮助。
// import preact
import { h, render, Component } from 'preact';
// import stylesheets for ipad & button
import style from './style';
import style_iphone from '../button/style_iphone';
// import jquery for API calls
import $ from 'jquery';
// import the Button component
import Button from '../button';
export default class Iphone extends Component {
//var Iphone = React.createClass({
// a constructor with initial set states
constructor(props){
super(props);
// temperature state
this.state.temp = "";
}
componentWillUpdate(){
this.fetchWeatherData();
}
// a call to fetch weather data via wunderground
fetchWeatherData = () => {
// API URL with a structure of :
ttp://api.wunderground.com/api/key/feature/q/country-code/city.json
var url =
"http://api.wunderground.com/api/mykey/conditions/q/UK/London.json";
$.ajax({
url: url,
dataType: "jsonp",
success : this.parseResponse,
error : function(req, err){ console.log('API call failed ' + err); }
})
}
// the main render method for the iphone component
render() {
// check if temperature data is fetched, if so add the sign styling to the page
const tempStyles = this.state.temp ? `${style.temperature} ${style.filled}` : style.temperature;
document.write(this.state.locate);
// display all weather data
return (
<div class={ style.container }>
<div class={ style.header }>
<div class={ style.city }>{ this.state.locate }</div>
<div class={ style.conditions }>{ this.state.cond }</div>
<span class={ tempStyles }>{ this.state.temp }</span>
</div>
<div class={ style.details }></div>
<div class= { style_iphone.container }>
{ this.state.display }
</div>
</div>
);
}
parseResponse = (parsed_json) => {
var location = parsed_json['current_observation']['display_location']['city'];
var temp_c = parsed_json['current_observation']['temp_c'];
var conditions = parsed_json['current_observation']['weather'];
// set states for fields so they could be rendered later on
this.setState({
locate: location,
temp: temp_c,
cond : conditions
});
}
}