React 页面请求axios的时候的loading效果

// 通过 reducer 中的变量控制 true, false

  1. 初始的时候为true, 页面刷新 (有loading效果) true
  2. axios 加载的时候 (有loading效果)true
  3. axios 加载完毕 (没有loading效果)false
import _ from 'loadsh'

const homeState = {
    loading: true,  // 控制loading效果
}

export default function homeIndex(state = homeState, action) {
    switch (action.type) {

        // 触发改变
        case 'LODING':
            console.log(action.payload, 'payload');  // true false
            return { ...state, ...{ loading: action.payload } }

        default:
            return state
    }
}
reducer 中: 
// dispath react-thunk 插件 可以使用函数 
// loading: 
export const loading = options => {
    return {
        type: 'LODING',
        payload: options
    }
}
axios中:
import axios from 'axios'
import { loading } from '@/action/home-index'  // 获取 

let cancelToken = axios.CancelToken
const cancel = []
const removePending = config => {
    for (let p in cancel) {
        if (cancel[p].u === config.url) {
            cancel[p].f()
        }
    }
}

// 请求拦截器 发送一个请求之前
axios.interceptors.request.use(config => {
    //在一个ajax发送前执行一下取消操作
    removePending(config)
    config.cancelToken = new cancelToken(c => {
        cancel.push({
            f: c,
            u: config.url,
        })
    })
    
    window.store.dispatch(loading(true))  // 加载的时候
    return config
}, error => {
    return Promise.reject(error)
})

//添加响应拦截器
axios.interceptors.response.use(response => {
    window.store.dispatch(loading(false)) // 加载完毕的时候
    return response
}, error => { })

使用的时候: 
import React, { PureComponent } from 'react';
import './styles.less'
import { connect } from 'react-redux'
import { recommend } from '@/action/home-index'

export default @connect(state => ({
    // 获取 reducer 中的外部 loading 变量 
    loading: state.homeIndex.loading,
}), {
    recommend
})
class extends PureComponent {
    componentDidMount() {
    	// 初始进来的时候 调用axios
        this.props.recommend()
    }
   	// 点击调用axios
    fn = () => {
        this.props.recommend()
    }

    render() {
        const { loading } = this.props

        return (
            <div className='home-shopping'>
                
                <button onClick={() => this.fn()}>
                    点击
                </button>

               <h1>
                {
                	// 由 truefalse 控制 loading效果
                    loading && '加载中........'
                }
               </h1>

            </div>
        )
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值