React技术栈-react使用的Ajax请求库实战案例

         React技术栈-react使用的Ajax请求库实战案例

                                  作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.常见的Ajax请求库

  温馨提示:
    React本身只关注于界面, 并不包含发送ajax请求的代码
    前端应用需要通过ajax请求与后台进行交互(json数据)
    react应用中需要集成第三方ajax库(或自己封装)

  常用的ajax请求库
    jQuery: 
      比较重, 如果需要另外引入,生产环境中不建议使用。
    axios: 
      轻量级, 建议使用,axios有以下特点:
        1>.封装XmlHttpRequest对象的ajax;
        2>.promise风格(then/catch);
        3>.可以用在浏览器端和node服务器端;
    fetch: 
      原生函数, 但老版本浏览器不支持
        1>.不再使用XmlHttpRequest对象提交ajax请求
        2>.为了兼容低版本的浏览器, 可以引入兼容库fetch.js

二.使用axios案例

1>.HTML源代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用axios案例</title>
</head>
<body>
    <div id="box1"></div>

    <!--导入 React的核心库-->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!--导入提供操作DOM的react扩展库-->
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <!--导入解析JSX语法代码转为纯JS语法代码的库-->
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <!--导入解析解析props属性的库-->
    <script type="text/javascript" src="../js/prop-types.js"></script>
    <!--导入axios库-->
    <script type="text/javascript" src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>

    <script type="text/babel">
        //1>.定义组件
        class MostStarRepo extends React.Component{
            state = {
                response_name:'',
                response_url:''
            }

            //在初始化阶段就异步发送请求。
            componentDidMount(){
                const url = `https://api.github.com/search/repositories?q=r&sort=stars`;
                //使用axios发送异步的Ajax请求
                axios.get(url)
                    .then(response => {
                        console.log(response);
                        const result = response.data;
                        //得到数据
                        const {name,html_url} = result.items[0];
                        //更新状态
                        this.setState({response_name:name,response_url:html_url});
                    })
                    //异常处理
                    .catch((error) => {
                        console.log(error.message);
                    })

            }

            render(){
                const {response_name,response_url} = this.state;
                if(!response_name){
                    return <h1>Loading....</h1>
                }else{
                    return <h1>Most star repo is <a href={response_url}>{response_name}</a></h1>
                }
            }
        }

        //2>.渲染组件
        ReactDOM.render(<MostStarRepo />,document.getElementById("box1"));


    </script>
</body>
</html>
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Axios的GET请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
Axios的POST请求

2>.浏览器打开以上代码渲染结果

三.使用fetch案例

1>.HTML源代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用axios案例</title>
</head>
<body>
    <div id="box1"></div>

    <!--导入 React的核心库-->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!--导入提供操作DOM的react扩展库-->
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <!--导入解析JSX语法代码转为纯JS语法代码的库-->
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <!--导入解析解析props属性的库-->
    <script type="text/javascript" src="../js/prop-types.js"></script>
    <!--导入axios库-->
    <script type="text/javascript" src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>

    <script type="text/babel">
        //1>.定义组件
        class MostStarRepo extends React.Component{
            state = {
                response_name:'',
                response_url:''
            }

            //在初始化阶段就异步发送请求。
            componentDidMount(){
                const url = `https://api.github.com/search/repositories?q=r&sort=stars`;
                //使用axios发送异步的Ajax请求
                // axios.get(url)
                //     .then(response => {
                //         console.log(response);
                //         const result = response.data;
                //         //得到数据
                //         const {name,html_url} = result.items[0];
                //         //更新状态
                //         this.setState({response_name:name,response_url:html_url});
                //     })
                //     //异常处理
                //     .catch((error) => {
                //         console.log(error.message);
                //     })

                //使用fetch发送异步的Ajax请求
                fetch(url)
                    .then(response => {
                        return response.json()
                    })
                    .then(data => {
                        //得到数据
                        const {name,html_url} = data.items[0];
                        //更新状态
                        this.setState({response_name:name,response_url:html_url});
                    })
                    //异常处理
                    .catch((error) => {
                        console.log(error.message);
                    })
            }

            render(){
                const {response_name,response_url} = this.state;
                if(!response_name){
                    return <h1>Loading....</h1>
                }else{
                    return <h1>Most star repo is <a href={response_url}>{response_name}</a></h1>
                }
            }
        }

        //2>.渲染组件
        ReactDOM.render(<MostStarRepo />,document.getElementById("box1"));


    </script>
</body>
</html>
fetch(url).then(function(response) {
  return response.json()
}).then(function(data) {
  console.log(data)
}).catch(function(e) {
  console.log(e)
});
Fetch的GET请求
fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
}).then(function(data) {
  console.log(data)
}).catch(function(e) {
  console.log(e)
})
Fetch的POST请求

2>.浏览器打开以上代码渲染结果

原文地址:https://www.cnblogs.com/yinzhengjie/p/12147531.html