react学习笔记--使用axios和fetch(实现Ajax)

react学习笔记–使用axios和fetch

这个案例是再github上查询到star数量最多的指定的repository。
react学习笔记--使用axios和fetch(实现Ajax)_第1张图片
在代码中是直接使用的bootcdn中的axios在线链接,实际使用应下载下来。


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Documenttitle>
head>

<body>
    <div id="example">div>

    <script src="../js/react.development.js">script>
    <script src="../js/react-dom.development.js">script>
    <script src="../js/prop-types.js">script>
    <script src="../js/babel.min.js">script>
    <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js">script>

    <script type="text/babel">
        class MostStarRepo extends React.Component {
      
            state = {
      
                repName: '',
                repUrl: ''
            }
            componentDidMount() {
      
                //发送异步请求
                const url =  `https://api.github.com/search/repositories?q=js&sort=stars`;

                axios.get(url).then(response => {
      
                  const result =  response.data;
                  console.log(result);
                  //选择第一条就是星星最多的
                  const {
      name,html_url} =  result.items[0];
                  this.setState({
      repName:name,repUrl: html_url});
                  
                })
                .catch((error) => {
      
                    alert(error.message);
                })
                /*fetch
                    fetch(url).then(response => {
                        return response.json()
                    }).then(data => {
                        const {name,html_url} =  data.items[0];
                        this.setState({repName:name,repUrl: html_url});
                     }) */
            }

            render() {
      
                const {
      repName,repUrl} = this.state;
                if(!repName){
      
                    return <h2>LOADING...</h2>
                }else{
      
                    return <h2>Most star repo is <a href={
      repUrl}>{
      repName}</a></h2>
                }
            }
        }
        ReactDOM.render(<MostStarRepo/>,document.getElementById('example'));
    script>
body>

html>

你可能感兴趣的:(#,React学习笔记)