// 通过 reducer 中的变量控制 true, false
- 初始的时候为true, 页面刷新 (有loading效果) true
- axios 加载的时候 (有loading效果)true
- 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>
{
// 由 true 和 false 控制 loading效果
loading && '加载中........'
}
</h1>
</div>
)
}
}