【问题标题】:printing dynamic variables before render在渲染之前打印动态变量
【发布时间】:2023-03-23 14:27:01
【问题描述】:

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

}

【问题讨论】:

    标签: javascript json reactjs api preact


    【解决方案1】:

    您应该使用componentDidMount() 方法。您不能在 componentWillUpdate() 方法中调用 setState。该方法用于:

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

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

    【讨论】: