Axios示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MostStart extends React.Component {
state = {
repoName: '',
repoUrl: ''
}
async componentDidMount() {
// 发送Ajax请求
const url = `https://api.github.com/search/repositories?q=r&sort=stars`
const { data: res } = await axios.get(url)
const { html_url, name } = res.items[0]
this.state.repoUrl = html_url
this.state.repoName = name
this.setState({ html_url, name })
}
render() {
const { repoName, repoUrl } = this.state

if (!repoName) { return <h2>LOADING....</h2> } else {
return <h2>Most star repo is <a href={repoUrl} target="_blank" rel="noopener noreferrer">{repoName}</a></h2>
}

}
}

Fetch示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class MostStart extends React.Component {
state = {
repoName: '',
repoUrl: ''
}
componentDidMount() {
// 发送Ajax请求
const url = `https://api.github.com/search/repositories?q=r&sort=stars`
fetch(url)
.then(response => {
return response.json()
})
.then(data => {
const { html_url, name } = data.items[0]
this.state.repoUrl = html_url
this.state.repoName = name
this.setState({ html_url, name })
})

}
render() {
const { repoName, repoUrl } = this.state

if (!repoName) { return <h2>LOADING....</h2> } else {
return <h2>Most star repo is <a href={repoUrl} target="_blank" rel="noopener noreferrer">{repoName}</a></h2>
}

}
}

搜索小Demo

https://github.com/changeclass/Tzk/tree/master/2020-11/14/code/react-app-ajax