本文是学习React笔记,对应视频为:https://www.bilibili.com/video/BV1oW41157DY 的 24 - 25 节。
需求:
1. 根据指定的关键字在github上搜索匹配的最受关注的库
2. 显示库名,点击链接查看库
3. 测试接口 https://api.github.com/search/repositories?q=r&sort=stars
一、使用axios实现Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax</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://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
<script src="babel.min.js"></script>
</head>
<body>
<div id="git"></div>
<script type="text/babel">
class MostStarRepo extends React.Component{
state = {
repoName: '',
repoUrl: ''
}
componentDidMount(){
//使用axios发送请求ajax请求
const url = `https://api.github.com/search/repositories?q=react&sort=stars`
axios.get(url)
//.post(url, {name: 'xxxx'})
.then(reponse => {
const result = reponse.data;
console.log(reponse)
const {name, html_url} = result.items[0];
//更新状态
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(<MostStarRepo/>, document.getElementById('git'))
</script>
</body>
</html>
二、使用fetch实现Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax</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://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
<script src="babel.min.js"></script>
</head>
<body>
<div id="git"></div>
<script type="text/babel">
class MostStarRepo extends React.Component{
state = {
repoName: '',
repoUrl: ''
}
componentDidMount(){
//使用axios发送请求ajax请求
const url = `https://api.github.com/search/repositories?q=react&sort=stars`
//使用fetch发送异步的ajax请求
fetch(url).then(reponse => {
return reponse.json()
}).then(data => {
const {name, html_url} = data.items[0];
//更新状态
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(<MostStarRepo/>, document.getElementById('git'))
</script>
</body>
</html>