fetch是基于Promise, 所以舊瀏覽器不支持 Promise,
Fetch 優(yōu)點主要有:
語法簡潔肿孵,更加語義化
基于標準 Promise 實現,支持 async/await
同構方便蒜焊,使用 isomorphic-fetch
基本書寫結構
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});
es6 箭頭寫法:
fetch(url).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
支持及兼容:
由于 IE8 是 ES3,需要引入 ES5 的 polyfill: es5-shim, es5-sham
引入 Promise 的 polyfill: es6-promise
引入 fetch 探測庫:fetch-detector
引入 fetch 的 polyfill: fetch-ie8
可選:如果你還使用了 jsonp科贬,引入 fetch-jsonp
可選:開啟 Babel 的 runtime 模式泳梆,現在就使用 async/await
Fetch polyfill 的基本原理是探測是否存在 window.fetch
方法,如果沒有則用 XHR 實現榜掌。這也是 github/fetch 的做法优妙,但是有些瀏覽器(Chrome 45)原生支持 Fetch,但響應中有中文時會亂碼憎账,老外又不太關心這種問題套硼,所以我自己才封裝了 fetch-detector
和 fetch-ie8
只在瀏覽器穩(wěn)定支持 Fetch 情況下才使用原生 Fetch。這些庫現在每天有幾千萬個請求都在使用胞皱,絕對靠譜邪意!
Fetch 常見坑
Fetch 請求默認是不帶 cookie 的,需要設置 fetch(url, {credentials: 'include'})
服務器返回 400反砌,500 錯誤碼時并不會 reject雾鬼,只有網絡錯誤這些導致請求不能完成時,fetch 才會被 reject宴树。
一個簡單的例子
//一個獲取電影列表的例子
import React, { Component } from 'react';
import {
Text,
View,
Image,
ListView,
ActivityIndicator,
TouchableHighlight
} from 'react-native';
import styles from '../Styles/Main';
import MovieDetail from './MovieDetail';
class MovieList extends Component {
constructor(props) {
super(props);
this.state = {
movies: [],
loaded: false,
count: 20,
start: 0,
total: 0,
};
this.dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
});
this.REQUEST_URL = 'https://api.douban.com/v2/movie/top250';
this.fetchData();
}
requestURL(
url = this.REQUEST_URL,
count = this.state.count,
start = this.state.start
) {
return (
`${url}?count=${count}&start=${start}`
);
}
fetchData() {
fetch(this.requestURL())
.then(response => response.json())
.then(responseData => {
let newStart = responseData.start + responseData.count;
this.setState({
movies: responseData.subjects,
loaded: true,
total: responseData.total,
start: newStart,
});
})
.done();
}
showMovieDetail(movie) {
this.props.navigator.push({
title: movie.title,
component: MovieDetail,
passProps: {movie},
});
}
renderMovieList(movie) {
return (
<TouchableHighlight
underlayColor="rgba(34, 26, 38, 0.1)"
onPress={() => this.showMovieDetail(movie)}
>
<View style={styles.item}>
<View style={styles.itemImage}>
<Image
source={{uri: movie.images.large}}
style={styles.image}
/>
</View>
<View style={styles.itemContent}>
<Text style={styles.itemHeader}>{movie.title}</Text>
<Text style={styles.itemMeta}>
{movie.original_title} ( {movie.year} )
</Text>
<Text style={styles.redText}>
{movie.rating.average}
</Text>
</View>
</View>
</TouchableHighlight>
);
}
loadMore() {
fetch(this.requestURL())
.then(response => response.json())
.then(responseData => {
let newStart = responseData.start + responseData.count;
this.setState({
movies: [...this.state.movies, ...responseData.subjects],
start: newStart
});
})
.done();
}
onEndReached() {
console.log(
`到底了策菜!開始:${this.state.start},總共:${this.state.total}`
);
if (this.state.total > this.state.start) {
this.loadMore();
}
}
renderFooter() {
if (this.state.total > this.state.start) {
return (
<View
style={{
marginVertical: 20,
paddingBottom: 50,
alignSelf: 'center'
}}
>
<ActivityIndicator />
</View>
);
} else {
return (
<View
style={{
marginVertical: 20,
paddingBottom: 50,
alignSelf: 'center'
}}
>
<Text
style={{
color: 'rgba(0, 0, 0, 0.3)'
}}
>沒有可以顯示的內容了:)</Text>
</View>
);
}
}
render() {
if (!this.state.loaded) {
return (
<View style={styles.container}>
<View style={styles.loading}>
<ActivityIndicator
size="large"
color="#6435c9"
/>
</View>
</View>
);
}
return (
<View style={styles.container}>
<ListView
renderFooter={this.renderFooter.bind(this)}
pageSize={this.state.count}
onEndReached={this.onEndReached.bind(this)}
initialListSize={this.state.count}
dataSource={this.dataSource.cloneWithRows(this.state.movies)}
renderRow={this.renderMovieList.bind(this)}
/>
</View>
);
}
}
export { MovieList as default };