美文网首页
14.react-ajax(axios)

14.react-ajax(axios)

作者: __疯子__ | 来源:发表于2020-05-21 14:05 被阅读0次

教程1-14完整项目地址 https://github.com/x1141300029/react-Todos.git

接口地址 https://jsonplaceholder.typicode.com/todos

接口返回数据如下:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  }
]

将咱们项目中的isCompleted修改为completed
开发软件为webstrom的同学,使用ctrl+shift+F进行全局搜索isCompleted然后进行修改即可
1.安装依赖

cnpm i -D axios

2.新建文件
2.1.src/services/index.js

import axios from 'axios'
import apis from './apis'
const ajax=axios.create({
    baseURL:apis.baseURL
});
//在这里还会做一些全局的拦截器处理
export const getTodos=()=>{
    return ajax.get(apis.getTodo)
};

2.2.src/services/apis.js

/**
 * 接口配置文件
 */
export  default {
    baseURL:'https://jsonplaceholder.typicode.com',
    //获取todos的接口
    getTodo:'/todos'
}

全局暴露 src/index.js(不建议使用)

import * as services from './services'
//挂载到组件上(全局)
React.Component.prototype.http=services;

局部引用 src/App.js

import {getTodos} from './services'
    // 调用接口 并获取数据
    getData=()=>{
        getTodos().then(res=>{
            if(res.status===200){
                this.setState({
                    todos:res.data
                })
            }else{
                console.log("数据加载失败")
            }
        }).catch((err)=>{
            console.log(err)
        })
    };

    /**
     *  在声明周期中进行请求
     */
    componentDidMount() {
        this.getData();
    }

3.添加loading加载
3.1.删除初始数据src/App.js

    constructor(props) {
        super(props);//必须继承父类所有内容
        this.state = {
            title: "待办事项",
            desc: "今日事,今日毕。",
            todos: [
              // # delete 开始删除
                {
                    id: 1,
                    title: "吃饭",
                    completed: true
                }, {
                    id: 2,
                    title: "睡觉",
                    completed: false
                }
              // # delete 删除结束
            ]
        }
    }

3.2.添加loading加载属性

    constructor(props) {
        super(props);//必须继承父类所有内容
        this.state = {
            title: "待办事项",
            desc: "今日事,今日毕。",
            todos: [],
            isLoading:false,//默认不显示loading加载  #insert 增加
        }
    }

3.3.在调用请求数据前将开启isLoading

    //调用接口 并获取数据
    getData=()=>{
        // # insert 增加开始
        this.setState({
            isLoading:true
        });
        // # insert 增加结束
        getTodos().then(res=>{
            if(res.status===200){
                this.setState({
                    todos:res.data
                })
            }else{
                console.log("数据加载失败")
            }
        }).catch((err)=>{
            console.log(err)
        })
    };

3.4.在请求结束后将结束isLoading

    //调用接口 并获取数据
    getData=()=>{
        this.setState({
            isLoading:true
        });
        getTodos().then(res=>{
            if(res.status===200){
                this.setState({
                    todos:res.data
                })
            }else{
                console.log("数据加载失败")
            }
        }).catch((err)=>{
            console.log(err)
        }).finally(()=>{      //#insert 开始
            this.setState({
                isLoading:false
            })
        })                         //#insert 结束
    };

3.5.在组件中添加loading状态

    render() {
        return (
            <Fragment>
                <TodoHeader desc={this.state.desc}>{this.state.title}</TodoHeader>
                <TodoInput addTodos={this.addTodos} btnText='ADD'/>
                # update 修改开始
                {
                    this.state.isLoading
                        ?
                        <div>loading...</div>
                        :
                        <TodoList
                            onCompletedChange={this.onCompletedChange}
                            todos={this.state.todos}
                        />
                }
                # update 修改结束
                <Like/>
            </Fragment>
        );
    }

相关文章

网友评论

      本文标题:14.react-ajax(axios)

      本文链接:https://www.haomeiwen.com/subject/bpyzohtx.html