0

我正在尝试编写一个 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
    });
}

}

4

1 回答 1

0

您应该使用该componentDidMount()方法。你不能调用方法setStatecomponentWillUpdate()该方法用于:

现在我们已经承诺更新。“要我在重新渲染之前做点什么吗?” 我们的组件问。不,我们说。别再打扰我们了。

您可以在此链接中找到更多详细信息: https ://engineering.musesfind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1

于 2018-02-24T00:40:53.113 回答