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

简介: 这篇文章介绍了在React应用中使用Axios和Fetch库进行Ajax请求的实战案例,展示了如何通过这些库发送GET和POST请求,并处理响应和错误。

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

一.常见的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>.浏览器打开以上代码渲染结果**

目录
相关文章
|
7月前
|
前端开发 JavaScript UED
React 图标库使用指南
本文详细介绍如何在 React 项目中使用 `react-icons` 等图标库,涵盖环境搭建、基础使用、常见问题与易错点、高级用法等内容,并通过代码案例进行说明。适合初学者和进阶开发者参考。
480 8
|
7月前
|
XML 前端开发 JavaScript
|
6月前
|
JSON 前端开发 JavaScript
Python中如何判断是否为AJAX请求
AJAX请求是Web开发中常见的异步数据交互方式,允许不重新加载页面即与服务器通信。在Python的Django和Flask框架中,判断AJAX请求可通过检查请求头中的`X-Requested-With`字段实现。Django提供`request.is_ajax()`方法,Flask则需手动检查该头部。本文详解这两种框架的实现方法,并附带代码示例,涵盖安全性、兼容性、调试及前端配合等内容,帮助开发者提升Web应用性能与用户体验。
91 0
|
8月前
|
前端开发 JavaScript
回顾前端页面发送ajax请求方式
回顾前端页面发送ajax请求方式
80 18
|
7月前
|
前端开发 API 开发者
Python Web开发者必看!AJAX、Fetch API实战技巧,让前后端交互如丝般顺滑!
在Web开发中,前后端的高效交互是提升用户体验的关键。本文通过一个基于Flask框架的博客系统实战案例,详细介绍了如何使用AJAX和Fetch API实现不刷新页面查看评论的功能。从后端路由设置到前端请求处理,全面展示了这两种技术的应用技巧,帮助Python Web开发者提升项目质量和开发效率。
147 1
|
7月前
|
资源调度 前端开发 JavaScript
React 测试库 React Testing Library
【10月更文挑战第22天】本文介绍了 React Testing Library 的基本概念和使用方法,包括安装、基本用法、常见问题及解决方法。通过代码案例详细解释了如何测试 React 组件,帮助开发者提高应用质量和稳定性。
249 1
|
8月前
|
前端开发 JavaScript Java
第6章:Vue中的ajax(包含:回顾发送ajax请求方式、vue-cli脚手架配置代理服务器)
第6章:Vue中的ajax(包含:回顾发送ajax请求方式、vue-cli脚手架配置代理服务器)
169 4
|
28天前
|
缓存 前端开发 数据安全/隐私保护
如何使用组合组件和高阶组件实现复杂的 React 应用程序?
如何使用组合组件和高阶组件实现复杂的 React 应用程序?
153 68
|
28天前
|
缓存 前端开发 Java
在 React 中,组合组件和高阶组件在性能方面有何区别?
在 React 中,组合组件和高阶组件在性能方面有何区别?
132 67
|
28天前
|
前端开发 JavaScript 安全
除了高阶组件和render props,还有哪些在 React 中实现代码复用的方法?
除了高阶组件和render props,还有哪些在 React 中实现代码复用的方法?
137 62