React-Ajax:根据指定的关键字在 github 上搜索匹配的最受关注的库
前置说明
- React 本身只关注于界面, 并不包含发送 ajax 请求的代码
- 前端应用需要通过 ajax 请求与后台进行交互(json 数据)
- react 应用中需要集成第三方 ajax 库(或自己封装)
常用的 ajax 请求库
- jQuery: 比较重, 如果需要另外引入不建议使用
- axios: 轻量级, 建议使用
a. 封装 XmlHttpRequest 对象的 ajax
b. promise 风格
c. 可以用在浏览器端和 node 服务器端 - fetch: 原生函数, 但老版本浏览器不支持
a. 不再使用 XmlHttpRequest 对象提交 ajax 请求
b. 为了兼容低版本的浏览器, 可以引入兼容库 fetch.js
react ajax的理解
- 一般将数据请求Ajax方法写在组件的hook函数componentDidMount 中,这样一旦页面加载完毕就开始执行Ajax函数。
- 从服务端获取数据库可以将数据存储在 state 中,再用 this.setState 方法重新渲染 UI。
- 当使用异步加载数据时,在组件卸载前使用 componentWillUnmount 来取消未完成的请求。
示例一实现效果
需求:
- 界面效果如下
- 根据指定的关键字在 github 上搜索匹配的最受关注的库
- 显示库名, 点击链接查看库
- 测试接口: https://api.github.com/search/repositories?q=r&sort=stars
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>11_ajax</title>
</head>
<body>
<div id="example"></div>
<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
<script type="text/babel">
class MostStarPepo extends React.Component{
state = {
repoName:'',
repoUrl:''
}
//初始化的时候就发出请求
componentDidMount(){
//发送异步的ajax请求
//使用axios 两个方法 get和post请求
const url = 'https://api.github.com/search2/repositories?q=r&sort=stars'
//sort是排序的意思 降序 从大到小
axios.get(url)
//post.(url,{}) 前面URL 后面对象 参数的键值对
.then(response =>{ //传一个回调函数
const result = response.data
//得到数据
const {name,html_url} = result.items[0]
//更新状态
this.setState({
repoName:name,
repoUrl:html_url,
})
})
.catch((error) =>{
alert(error.message)
})
//也可使用fetch发送异步的ajax请求
/*fetch(url)
.then(response =>{ //传一个回调函数
return response.json()
})
.then(data =>{
//得到数据
const {name,html_url} = data.items[0]
//更新状态
console.log(data)
this.setState({
repoName:name,
repoUrl:html_url,
})
})*/
}
render(){
const {repoName,repoUrl} =this.state
if(!repoName){
return(
<h2>LOADING...</h2>
)
}else {
return <h2>Most star repo is<a href={repoUrl}>{repoName}</a></h2>
}
}
}
ReactDOM.render(<MostStarPepo/>,document.getElementById('example'))
</script>
</body>
</html>
运行截图
点击下图链接查看库
示例二实现效果
需求:
- 获取 Github 用户最新 gist 共享描述
方法一:
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')
);
方法二:
class UserGist extends React.Component {
constructor(props) {
super(props);
//在state设置两个属性,以便后续通过state对象来对其进行修改
this.state = {username: '', lastGistUrl: ''};
//绑定挂载事件
this.componentDidMount = this.componentDidMount.bind(this);
}
componentDidMount() {
//接下来操作state时上下文对象发生改变,此处拿到操作句柄
var that = this;
//ajax请求
this.serverRequest = $.ajax({
url: this.props.source,
type:"GET",
dataType: 'jsonp',
success: function (result) {
console.log(result.data);
var lastGist = result.data[0];
//此处的上下文发生改变,this的指针指向发生了变化,通过上述定义的that来操作
that.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
})
}
})
}
//卸载React组件时,把多余请求关闭,以免影响其他框架或组件的操作
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
return (
<div>
{this.state.username} 用户最新的 Gist 共享地址:
<a href={this.state.lastGistUrl} rel="nofollow">{this.state.lastGistUrl}</a>
</div>
);
}
}
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.getElementById('example')
);