本文重点在 fetch
基础使用、配置、实战,如果你很熟练了,可以直接 pass
fetch
使用我在 easy-mock
上准备了模拟数据
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
是浏览器内置对象,所以我们不用安装包,直接使用
注意需要执行一次
res.json()
方法才能获取数据
我们获取数据后,设置 state
,然后正常数据 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 方式获取数据" onClickCapture={this.handleClick} /> <ul> {this.state.users && this.state.users.map((item, index) => ( <li key={index.toString()}>{item.name}</li> ))} </ul> </div> ) }}复制代码
打印
我们来好好的看下这个 fetch()
全局方法
我举两个自定义例子,大家体会下
Headers
请求头协议说明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
请求头协议说明body
数据,格式 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))复制代码
这里就类似我们第一个基础例子了
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
数据需要格式化 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()
这个方法不要忘记调用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 方式获取数据" 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 业务层
很有可能复用性很高)。
如果考虑兼容性,所以我们还是用第三方组件
感觉 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 组件方式 获取数据" 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复制代码
联系客服