Axios:React & Javascript

本文详细介绍了如何在React应用中使用Axios进行HTTP请求,包括安装Axios、使用Promise、渲染获取的数据、转换数据、更新时获取数据、新增数据、删除数据、错误处理、设置全局拦截器以及配置局部默认参数等关键步骤,帮助开发者掌握Axios在实际项目中的应用。
摘要由CSDN通过智能技术生成

Axios——用于进行http request

https://github.com/axios/axios#typescript

安装Axios

npm install axios --save

Axios+Promise

import axios from 'axios';
componentDidMount(){
        //get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response=>{
                console.log(response);
            });
            //promise保证在get操作完成后执行.then操作
    }

Redering Fetch data

state中建立array保存传入的内容;
将传入的array用map变为array of < Post />;
将此放入JSX中;

import React, { Component } from 'react';

import Post from '../../components/Post/Post';
import FullPost from '../../components/FullPost/FullPost';
import NewPost from '../../components/NewPost/NewPost';
import './Blog.css';
import axios from 'axios';

class Blog extends Component {
    state={
        posts:[]
    }

    componentDidMount(){
        //get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response=>{
                this.setState({posts:response.data});
            });
            //promise保证在get操作完成后执行.then操作
    }


    render () {
        const posts = this.state.posts.map( //转为array
            post=>{
                return <Post title={post.title} key={post.id}/>
            }
        );
        return (
            <div>
                <section className="Posts">
                    {posts}
                </section>
                <section>
                    <FullPost />
                </section>
                <section>
                    <NewPost />
                </section>
            </div>
        );
    }
}

export default Blog;

Tranforming data——处理get到的数据

将得到的response取前4;
使用map添加一个author属性;

componentDidMount(){
        //get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response=>{
                const posts=response.data.slice(0,4);
                const updatedPosts = posts.map(post=>{
                    return {
                        ...post,
                        author:'JQ'
                    };
                })
                this.setState({posts:updatedPosts});
            });
            //promise保证在get操作完成后执行.then操作
    }

Fetching data on update

每次选中一个post,进行get得到该data;

注意点
使用didupdate——配合setstate,会进入死循环;
因为setstate对state进行了改变,引起了re-render,调用update,而update又调用setstate……;
故需要加入条件判断——防止死循环

componentDidUpdate(){
        if(this.props.id){
            if( !this.state.loadedPost||(this.state.loadedPost && this.state.loadedPost.id !==this.props.id)){
                axios.get(`https://jsonplaceholder.typicode.com/posts/${this.props.id}`)
                .then(response=>this.setState({loadedPost:response.data}));
            }
        };
    }

Posting data

Axios.post(url,data);

postDataHandler=()=>{
        const post={
            title:this.state.title,
            body:this.state.content,
            author:this.state.author
        };
        Axios.post('https://jsonplaceholder.typicode.com/posts',post).  //加入要传入的data
            then(response=>{
                console.log(response);
            });
    }

Delete

    deletePostHandler=()=>{
        axios.delete(`https://jsonplaceholder.typicode.com/posts/${this.props.id}`).then(response=>console.log(response));
    }

Catch Error

    componentDidMount(){
        //get为异步——即无法使用变量保存(因为执行该语句后变量中还未保存数据)
        axios.get('https://jsonplaceholder.typicode.com/postsss')
            .then(response=>{
                const posts=response.data.slice(0,4);
                const updatedPosts = posts.map(post=>{
                    return {
                        ...post,
                        author:'JQ'
                    };
                })
                this.setState({posts:updatedPosts});
            })
            .catch(err=>console.log(err));
            //promise保证在get操作完成后执行.then操作
    }

Interceptor ——Execute code globally

可以对所有component 的requset和response进行操作;

axios.interceptors.request.use(requset=>{
  console.log(requset);
  return requset;
},error=>{
  console.log(error);
  return Promise.reject(error);
});


axios.interceptors.response.use(response=>{
  console.log(response)
  return response;
},error=>{
  console.log(error);
  return Promise.reject(error);
});

Get rid of an interceptor

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

https://github.com/axios/axios#interceptors

Setting a Default global configuration

设置全局的默认url;
后面get,post等只需要在baseURL 的基础上写url即可;

axios.defaults.baseURL="https://jsonplaceholder.typicode.com/";
axios.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
axios.defaults.headers.post['Content-Type'] ='application/json';

进行局部default

在别的js中import该instance,即可实现局部default;

import axios from 'axios';

const instance =axios.create({
  baseURL:'https://jsonplaceholder.typicode.com/'
});

instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN 123321';

export default instance;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值