React 使用 fetch 请求天气

中国天气网(http://www.weather.com.cn)提供了查询天气的 API,通过传入城市 id, 可以获得当前城市的天气信息,API 相关信息如下:

规格  描述
主机地址 http://www.weather.com.cn
访问方法 GET
路径 data/cityinfo/{城市编号}.html
返回结果 JSON 格式,包含 city、temp1、temp2、weather等信息

 

 

 

 

 

 

返回结果格式如下:

在请求天气数据的时候有几个问题需要注意:

1. 使用浏览器原生支持的 fetch 函数来请求 api,同时为了解决跨域问题,需要在项目的 package.json 文件中添加一行:

  "proxy": "http://www.weather.com.cn/"

2. 城市编号的查询:直接在百度中直接查询当前城市的天气,如下:

点击进入详情,地址栏中显示的编号即为城市id,如下:

3. 因为返回的数据是 JSON 格式,所以在 fetch 函数请求到结果之后,需要使用 res.json() 来获取 JSON 数据,如下:

 

具体天气组件代码如下:

 1 import React from 'react'
 2 
 3 class Weather extends React.Component {
 4   state = {
 5     weather: null
 6   }
 7   componentDidMount () {
 8     const cityCode = 101210101
 9     const url = `/data/cityinfo/${cityCode}.html`
10     fetch(url).then(res => {
11       res.json().then(resJson => {
12         this.setState({
13           weather: resJson.weatherinfo
14         })
15       })
16     })
17   }
18   render () {
19     const {  weather } = this.state
20     return (
21       <div>
22         { this.state.weather
23           ? <ul>
24               <li>city: { weather.city }</li>
25               <li>cityid: { weather.cityid }</li>
26               <li>ptime: { weather.city }</li>
27               <li>weather: { weather.weather }</li>
28               <li>temp1: { weather.temp1 }</li>
29               <li>temp2: { weather.temp2 }</li>
30             </ul>
31           : <p>暂无数据</p>
32         }
33       </div>
34     )
35   }
36 }
37 
38 export default Weather

 打印出返回的结果如下:

 

参考:《深入浅出 React 和 Redux 》第七章 《Redux 和服务器通信》

 

posted @ 2017-08-14 16:40  Raychan  阅读(2127)  评论(0编辑  收藏  举报