中國天氣網(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 和服務器通信》