中國天氣網(提供了查詢天氣的 api,通過傳入城市 id, 可以獲得當前城市的天氣資訊,api 相關資訊如下:
規格 描述
主機位址
訪問方法
get路徑
data/cityinfo/.html
返回結果
json 格式,包含 city、temp1、temp2、weather等資訊
返回結果格式如下:
在請求天氣資料的時候有幾個問題需要注意:
1. 使用瀏覽器原生支援的 fetch 函式來請求 api,同時為了解決跨域問題,需要在專案的 package.json 檔案中新增一行:
3. 因為返回的資料是 json 格式,所以在 fetch 函式請求到結果之後,需要使用 res.json() 來獲取 json 資料,如下:
具體天氣元件**如下:
1 import react from 'react'23列印出返回的結果如下:class weather extends react.component
7componentdidmount () .html`
10 fetch(url).then(res =>)
15})
16})17}
18render () = this
.state
20return(21
22
3334)35
}36}37
38 export default weather
參考:《深入淺出 react 和 redux 》第七章 《redux 和伺服器通訊》
React 實現fetch取消 中止請求
專案 ant.design pro umijs dva 新建乙個abortdispath.js檔案 export const abortdispatch payload,dispatch const cancellation newpromise reject return promise.race...
React網路請求fetch之post請求
本節介紹下react下fetch的post請求 1 編寫服務端 載入express模組 var express require express 載入path路徑處理核心模組 var path require path 載入body parser中介軟體 var bodyparser require ...
React中fetch 基本使用
react中fetch 基本使用 一 fetch fetch是一種xmlhttprequest的一種替代方案,在工作當中除了用ajax獲取後台資料外我們還可以使用fetch axios來替代ajax 二 fetch的基本使用 fetch url then res then data catch e ...