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

梦想与她 提交于 2020-01-01 04:44:19

// 通过 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>
        )
    }
}


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!