fetch是基于Promise, 所以旧浏览器不支持 Promise,
Fetch 优点主要有:
语法简洁,更加语义化
基于标准 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
只在浏览器稳定支持 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 };