React Ajax
React 有无自己的ajax 库以及原因
React 没有封装的自己的ajax 库,主要原因是React 的目的在于只负责 UI视图层 。
官方是这样的使用 ajax 的,如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
class UserGist extends React.Component {
constructor(props) {
super(props);
this.state = {username: '', lastGistUrl: ''};
}
componentDidMount() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
return (
<div>
{this.state.username} 用户最新的 Gist 共享地址:
<a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
</div>
);
}
}
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.getElementById('example')
);
</script>
</body>
</html>
由此可见,React官方并没有封装自己的 ajax 库,而是引入的第三方库。那么,如何 React 应该选用哪个第三库会有更好的性能呢?
React 选用 ajax第三方库
1.JQuery Ajax
用Jquery 作为第三方库支持,有点大材小用了,为了引入 ajax 而把整个JQuery库全部引入,增加项目容量,不利于优化,因此不是最佳选择。
2.引入Zepto (轻量级的Jquery)
3.封装 原生xhr 。
推荐
自己封装 原生XHR 不失为一种很好的优化方案。不但可以实现自产自足、自供自给比较完美的项目优化方式,还可以较完美的对接项目需求。
4.axios
(推荐)
import React, { Component } from 'react';
import axios from '../model/axios';
class Axios extends Component {
constructor(props){
super(props);
this.state = {
list: []
}
}
getData = () => {
axios.get('https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list')
.then((response) => {
this.setState({
list: response.data
})
})
.catch(function (error) {
console.log(error);
});
}
render(){
return (
<div>
<button onClick={this.getData}>获取axios数据</button>
{
this.state.list.map((item,key) => {
return (
<li key={key}>
{item.title}
</li>
)
})
}
</div>
)
}
}
export default Axios;
5.fetch