React 学习笔记_19(在React中使用Axios调用JSON-Server数据)

简介

axios 是一个基于 Promise 的 HTTP 客户端,专门服务于浏览器和 node.js 。

功能

在浏览器中传送 XMLHttpRequests 请求在 node.js 中传送 http 请求支援 Promise API拦截请求和响应转换请求和响应资料自动转换 JSON 资料格式

建立Axios

使用JSON-Server建立一个数据库并且使用Axios对数据库中的数据进行操作。

Step 1 : 建立一个React Project并安装Axios

npm install axiosyarn add axios

Step 2 : 建立Axios的Component以提供呼叫

import _axios from "axios"const axios = (baseURL) => {    //建立一个自定义的axios    const instance = _axios.create({            baseURL: baseURL || 'http://localhost:3003', //JSON-Server端口位置            timeout: 1000,        });     return instance;}export {axios};export default axios();

Axios API实例

运用axios的API对JSON-Server数据库中的数据进行操作。

GET (取得资料)

import React from "react";import axios from "./axios";class App extends React.Component{    GET = async() => {        try         {            //取得数据库http://localhost:3003/posts的数据            const Data = await axios.get("/posts");             console.log(Data.data);        }         catch (error)         {            alert("GET Error!!");            }      };        render()    {        return(            <div className="get">                <button onClick={this.GET}>Get</button>            </div>        );    };};

当按下GET按钮后取得http://localhost:3003/posts的数据
http://img2.58codes.com/2024/20124767yYz0dITpkM.png

POST (新增资料)

import React from "react";import axios from "./axios";class App extends React.Component{    constructor(props)    {        super(props);        this.state = {            id:"",            title : "",            author : ""        }    };    handleChange = (e) => {        //Step 1:取得输入的数值        const value = e.target.value;        //Step 2:取得输入的input名子        const name = e.target.name;        //Step 3:更改State数据        this.setState({            [name]:value        });    };    //-------------------------------------------------//    POST = () => {        //Step 1:取得state数据        const product = {...this.state};        //Step 2:新增到JSON-Server数据库中         axios.post("/posts",product);    };    //-------------------------------------------------//                render()    {        retrun(            <div className="post">                    <label>title</label>                    <textarea                       name="title"                       value={this.state.title}                       onChange={this.handleChange}                    />                    <label>author</label>                    <textarea                       name="author"                       value={this.state.author}                       onChange={this.handleChange}                    />                    <button onClick={this.POST}>POST</button>             </div>        );    };};

http://img2.58codes.com/2024/20124767FptbxMFmcf.png

使用GET按钮来取得当前数据库数据以确认是否新增了新的数据到数据库中
http://img2.58codes.com/2024/20124767t20rqq0hjw.png

PUT (更新资料)

import React from "react";import axios from "./axios";class App extends React.Component{    constructor(props)    {        super(props);        this.state = {            id:"",            title : "",            author : ""        }    };    handleChange = (e) => {        //Step 1:取得输入的数值        const value = e.target.value;        //Step 2:取得输入的input名子        const name = e.target.name;        //Step 3:更改State数据        this.setState({            [name]:value        });    };    //-------------------------------------------------//    PUT = () => {        //Step 1:取得state数据        const product = {...this.state};        //Step 2:更新指定JSON-Server数据库中指定的id数据        axios.put(`posts/${this.state.id}`,product)    };    //-------------------------------------------------//                render()    {        return(             <div className="put">                    <label>ID</label>                    <input                       type="text"                       name="id"                       value={this.state.id}                       onChange={this.handleChange}                    />                    <label>title</label>                    <textarea                       name="title"                       value={this.state.title}                       onChange={this.handleChange}                    />                    <label>author</label>                    <textarea                       name="author"                       value={this.state.author}                       onChange={this.handleChange}                    />                    <button onClick={this.PUT}>PUT</button>                </div>        );    }; };    

http://img2.58codes.com/2024/20124767nprICLCMug.png
使用GET按钮来取得当前数据库数据以确认是否更新了指定id的数据
http://img2.58codes.com/2024/20124767Gke5DLFMWD.png

DELETE (删除资料)

import React from "react";import axios from "./axios";class App extends React.Component{    constructor(props)    {        super(props);        this.state = {            id:"",            title : "",            author : ""        }    };    handleChange = (e) => {        //Step 1:取得输入的数值        const value = e.target.value;        //Step 2:取得输入的input名子        const name = e.target.name;        //Step 3:更改State数据        this.setState({            [name]:value        });    };    //-------------------------------------------------//    Delete = () => {        const product = {...this.state};        axios.delete(`posts/${this.state.id}`,product)    };    //-------------------------------------------------//        render()    {        return(            <div className="delete">                    <label>ID</label>                    <input                       type="text"                       name="id"                       value={this.state.id}                       onChange={this.handleChange}                    />                    <button onClick={this.Delete}>Delete</button>            </div>        );    };   };    

指定要删除数据的id:
输入指定要删除的id
使用GET按钮来取得当前数据库数据以确认是否将指定id的数据删除
http://img2.58codes.com/2024/20124767tfEGNs83Qv.png

参考资料 :
GitHub-axios
axios 基本使用 & Config
Axios Crash Course | HTTP Library


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章