4、React发送Ajax请求
Axios示例
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示例
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
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小康博客!
评论
TwikooDisqusjs









