本文重點在 fetch
基礎(chǔ)使用、配置、實戰(zhàn),如果你很熟練了,可以直接 pass
fetch
使用我在 easy-mock
上準備了模擬數(shù)據(jù)
www.easy-mock.com/mock/59801f…
[ { "id": "610000200102261253", "name": "薛洋" }, { "id": "350000199603020600", "name": "許磊" }, { "id": "310000198105081812", "name": "崔娟" }, { "id": "820000197101010860", "name": "石霞" }]復制代碼
一個列表,兩個字段 id
name
fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all'' ) .then(res => res.json()) .then(data => { console.log(data) this.setState({users: data}) }) .catch(e => console.log(''錯誤:'', e))復制代碼
fetch
是瀏覽器內(nèi)置對象,所以我們不用安裝包,直接使用
注意需要執(zhí)行一次
res.json()
方法才能獲取數(shù)據(jù)
我們獲取數(shù)據(jù)后,設(shè)置 state
,然后正常數(shù)據(jù) render
就行,完整代碼
import React, {Component} from ''react''class RequestView extends Component { constructor(props) { super(props) this.state = {users: []} this.handleClick = this.handleClick.bind(this) } handleClick() { fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all'' ) .then(res => res.json()) .then(data => { console.log(data) this.setState({users: data}) }) .catch(e => console.log(''錯誤:'', e)) } render() { return ( <div> <input type="button" value="點擊 http-get 方式獲取數(shù)據(jù)" onClickCapture={this.handleClick} /> <ul> {this.state.users && this.state.users.map((item, index) => ( <li key={index.toString()}>{item.name}</li> ))} </ul> </div> ) }}復制代碼
打印
我們來好好的看下這個 fetch()
全局方法
我舉兩個自定義例子,大家體會下
Headers
請求頭協(xié)議說明let initHeaders = new Headers()initHeaders.append(''Accept'', ''application/json, text/plain, */*'')initHeaders.append(''Cache-Control'', ''no-cache'')initHeaders.append(''Content-Type'', ''application/x-www-form-urlencoded'')復制代碼
application/x-www-form-urlencoded
init
配置let data = {uid: 1011}let body = `uid=${data.uid}`const init = { method: ''POST'', credentials: ''include'', // cookies cache: ''no-cache '', // cookies headers: initHeaders, body}復制代碼
method
指定 POST
方式credentials: ''include''
表示每次都帶上 cookies
headers
請求頭協(xié)議說明body
數(shù)據(jù),格式 key=val&key=val&key=val
fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login'', init) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log(''錯誤:'', e))復制代碼
這里就類似我們第一個基礎(chǔ)例子了
Headers
let initHeaders = new Headers()initHeaders.append(''Accept'', ''application/json, text/plain, */*'')initHeaders.append(''Cache-Control'', ''no-cache'')initHeaders.append(''Content-Type'', ''application/json;charset=UTF-8'')復制代碼
Content-Type
類型需要定義成 application/json;charset=UTF-8
init
let data = {uid: 1011}let body = JSON.stringify(data, null, 2)const init = { method: ''POST'', credentials: ''include'', // cookies cache: ''no-cache '', // cookies headers: initHeaders, body}復制代碼
json
數(shù)據(jù)需要格式化 JSON.stringify(data, null, 2)
fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login'', init) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log(''錯誤:'', e))復制代碼
代碼
import React, {Component} from ''react''class RequestView extends Component { constructor(props) { super(props) this.state = {user: null} this.handlePostForm = this.handlePostForm.bind(this) this.handlePostJSON = this.handlePostJSON.bind(this) } handlePostForm() { let initHeaders = new Headers() initHeaders.append(''Accept'', ''application/json, text/plain, */*'') initHeaders.append(''Cache-Control'', ''no-cache'') initHeaders.append(''Content-Type'', ''application/x-www-form-urlencoded'') let data = {uid: 1011} let body = `uid=${data.uid}` const init = { method: ''POST'', credentials: ''include'', // cookies cache: ''no-cache '', // cookies headers: initHeaders, body } fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login'', init ) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log(''錯誤:'', e)) } handlePostJSON() { let initHeaders = new Headers() initHeaders.append(''Accept'', ''application/json, text/plain, */*'') initHeaders.append(''Cache-Control'', ''no-cache'') initHeaders.append(''Content-Type'', ''application/json;charset=UTF-8'') let data = {uid: 1011} let body = JSON.stringify(data, null, 2) const init = { method: ''POST'', credentials: ''include'', // cookies cache: ''no-cache '', // cookies headers: initHeaders, body } fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login'', init ) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log(''錯誤:'', e)) } render() { return ( <div> <input type="button" value="點擊 http-post form 表單" onClickCapture={this.handlePostForm} /> <br /> <input type="button" value="點擊 http-post json raw 格式" onClickCapture={this.handlePostJSON} /> {this.state.user && ( <ul> <li>ID: {this.state.user.id}</li> <li>Name: {this.state.user.name}</li> </ul> )} </div> ) }}export default RequestView復制代碼
動圖效果
async / wait
async handleClick() { try { const res = await fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all'' ) const users = await res.json() this.setState({users}) } catch (error) { console.log(''錯誤'', error) }}復制代碼
async
res.json()
這個方法不要忘記調(diào)用try ... catch ...
代碼
import React, {Component} from ''react''class RequestView extends Component { constructor(props) { super(props) this.state = {users: []} this.handleClick = this.handleClick.bind(this) } async handleClick() { try { const res = await fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all'' ) const users = await res.json() this.setState({users}) } catch (error) { console.log(''錯誤'', error) } } render() { return ( <div> <input type="button" value="點擊 async / await 方式獲取數(shù)據(jù)" onClickCapture={this.handleClick} /> <ul> {this.state.users && this.state.users.map((item, index) => ( <li key={index.toString()}>{item.name}</li> ))} </ul> </div> ) }}export default RequestView復制代碼
打印
好像 fetch
很強啊,不用安裝包,全局方法直接用,但是有一個小問題,對瀏覽器的依賴,先看下 caniuse 平臺的報告:
IE
全陣亡,低版本 Safari
兼容問題,Firefox
Chrome
Opera
如果特性不開的話也會出問題,懂的同學說可以瀏覽器配置和打 polyfill
補丁,但是這樣需要自己做很多工作,如果你的代碼需要跑到 node
端呢(因為API 業(yè)務(wù)層
很有可能復用性很高)。
如果考慮兼容性,所以我們還是用第三方組件
感覺 Star
不是很多么。。。
接著往下看
README 里說了各種平臺支持、知名項目也在用
是真的么。。。
接著往下看
打開文件 package.json
來看下這兩個包
指向了 github/fetch
好多 Star 看著就放心,大家用吧
yarn add cross-fetch復制代碼
import React, {Component} from ''react''import fetch from ''cross-fetch''class RequestView extends Component { constructor(props) { super(props) this.state = {users: []} this.handleClick = this.handleClick.bind(this) } async handleClick() { try { const res = await fetch( ''https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all'' ) const users = await res.json() this.setState({users}) } catch (error) { console.log(''錯誤'', error) } } render() { return ( <div> <input type="button" value="點擊 cross-fetch 組件方式 獲取數(shù)據(jù)" onClickCapture={this.handleClick} /> <ul> {this.state.users && this.state.users.map((item, index) => ( <li key={index.toString()}>{item.name}</li> ))} </ul> </div> ) }}export default RequestView復制代碼