使用Ajax在React中打开天气数据 [英] Open Weather data in React using Ajax

查看:175
本文介绍了使用Ajax在React中打开天气数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于打开天气图当前天气数据API ,我正在尝试将当前天气数据输入我的使用ajax的React.js应用程序,提取给定城市的当前临时值,然后在我的组件中呈现该值。

Given the Open Weather Map current weather data API, I'm trying to pull in current weather data into my React.js app using ajax, extract the current temp value for a given city, and then render that value in my component.

我正在使用的测试JSON数据在这个网址:
http:// api .openweathermap.org / data / 2.5 / weather?id = 5391997& units = imperial

The test JSON data that I'm working with is at this url: http://api.openweathermap.org/data/2.5/weather?id=5391997&units=imperial

var CityGrid = React.createClass({
  componentDidMount: function() {
    $.ajax({
      url: 'http://api.openweathermap.org/data/2.5/weather?id=5391997', 
      // ^^ this should get a variable where id=5391997 is set
      dataType: 'json',  
      success: function(data) {
          this.setState({temp: data.main.temp});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState:function(){
    return{
      cities:[
        { 
          name: "San Francisco",
          id: 5391997,
          temp: 50,  // << this should receive value from ajax call
          UTCOffset:-7,
          address: 999 Nathan Lane,
          phone: 555-5555
        },
        // 12 more city objects in this array, removed for brevity
    ]}
},
render: function() {
    console.log(this.state.temp); // << this returns the right temp
    // for San Francisco, because I hardcoded the value into the url
    return(
        <div className="city-grid">
        {this.state.cities.map(function(city,i){
          return(
            <CityRow key={i} name={city.name} temp={city.temp}
            UTCOffset={city.UTCOffset} address={city.address} 
            phone={city.phone}/>
          );
        })}
      </div>
    );
  }
});

module.exports = CityGrid;

我的问题:


  1. 如何提取临时值?在我的渲染函数中,console.log返回JSON对象,这意味着数据已绑定并可在我的渲染函数中访问。但是,当我试图获得温度时,我希望它是 this.state.data.main.temp ,我得到数据未定义的错误。然后,我希望能够在我的城市对象中为这12个城市中的每个城市的 id:5391997,设置此值。

  1. How to extract the temp value? In my render function, console.log returns the JSON object, which means the data has been bound and can be accessed in my render function. However, when I try to get the temperature, which I expect to be something like this.state.data.main.temp, I get errors that "data is undefined." I would then like to be able to set this value in my cities object at id: 5391997, for each of the 12 cities.

UPDATE ^^这个问题解决了:@dkurbz建议在我的ajax成功方法中将状态设置为temp对我来说很好。

UPDATE ^^ This is solved: @dkurbz suggestion to set the state as temp in my ajax success method works fine for me.


  1. 我也面临着如何为每个城市设置唯一网址的挑战。在我的ajax调用中,有 id = 5391997 ,我想从城市对象中获取并将我的ajax url更改为'baseURl'+ this.props。 id +'& units = imperial'。我完全不知道如何做到这一点。

  1. I'm also having a challenge with how to set the url uniquely for each city. In my ajax call, there is id=5391997, which I would like to get from the cities objects and change my ajax url to something like 'baseURl' + this.props.id + '&units=imperial'. I'm at a total loss about how to do this.

UPDATE ^^这就是我的地方我目前卡住了。

UPDATE ^^ This is where I'm currently stuck.

推荐答案

这可能会有一些错误,但我认为它应该让你非常接近。

There might be some errors with this, but I think it should get you pretty close.

var React = require("react");
var $ = require("jquery");

var City = React.createClass({
    propTypes: {
        id: React.PropTypes.string.isRequired,
        units: React.PropTypes.string
    },

    getInitialState: function () {
        return {
            data: {},
            fetching: false
        };
    },

    getDefaultProps: function () {
        return {
            units: "imperial"
        };
    },

    render: function () {
        return (
            <div class="city">
                {this.state.fetching ? "Downloading data..." : this.state.data.main.temp}
            </div>
        );
    },

    componentWillMount: function () {
        $.ajax({
            url: "http://api.openweathermap.org/data/2.5/weather?id="+this.props.id+"&units="+this.props.units,
            dataType: "json",
            beforeSend: function () {
                this.setState({fetching: true});
            },
            success: function (data) {
                this.setState({data: data});
            },
            error: function (xhr, status, err) {
                console.error(xhr, status, err.toString());
            },
            complete: function () {
                this.setState({fetching: false});
            },
            context: this
        });
    }
});

var CityGrid = React.createClass({
    propTypes: {
        cityIds: React.PropTypes.array.isRequired
    },

    renderCity: function (cityId) {
        return <City id={cityId} />;
    },

    render: function () {
        return (
            <div class="city-grid">
                {this.props.cityIds.map(this.renderCity)}
            </div>
        );
    }
});

有人说......这不是正确的解决方案。应该将ajax调用移到组件之外(你看过Flux,还是其他一些可以给你模型或商店概念的库?),然后应该将返回的数据转换/标准化为一个单元结构以某种方式,然后传递给City组件作为道具(并且只有有意义/你关心的道具)。这样,City组件可以不知道其数据来自何处。理论上,您应该能够使用来自其他来源,多个来源,虚拟数据等的一些数据来呈现城市。但我不打算为您编写所有内容;)

That being said... this isn't The Right Solution. The ajax call should be moved outside of the component (have you looked into Flux, or some other library that would give you the concept of a Model or a Store?), the returned "data" should then be transformed/normalized into a flat structure somehow, and then passed to the City component as props (and only the props that make sense/that you care about). This way, the City component can be agnostic about where its data comes from. You should, in theory, be able to render a City with some data from another source, multiple sources, dummy data, etc. But I wasn't going to go and code all that for you ;)

这篇关于使用Ajax在React中打开天气数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆