dva-loading Github https://github.com/dvajs/dva/tree/master/packages/dva-loading
npm install dva-loading --save
loading
- 异步加载方法的状态:异步加载中状态为 true,异步加载完成状态为 false
- loading只针对 models里面的 effects里面的异步方法有效
- 避免了异步自己手动的 setState loading
‘user/query’ 是个 effects里面,异步请求后台的方法
loading: {
global: true, // 全局的 loading,effect里面有一个 true,global就为 true
effects: { 'user/query': true }, // 有哪些 effect在loading
models: { 'user/query', true }, // 有哪些model在loading
}
global
- 一个页面中,可能同时有多个异步加载,只要有一个异步加载没有完成,global 都是 true
- 但是 effects 中加载完成的,异步方法都会变成 false,只有没加载完成的异步方法才是 true
- 根据 loading.effects 对象判断当前 effects中的异步加载是否完成,并将该值传递给 组件的 props
loading.effects
异步请求中loading变量会为true,完成后会变成false
// 监听某个模块下的所有异步请求
const isLoading = loading.models.list;
// 监听单个effect
const isLoading = loading.effects['list/asyncTable']
// 全局的 loading
const globalLoading = loading.global;
index.js
/src/index.js
import dva from 'dva';
import { createBrowserHistory as BrowserHistory } from 'history';
import dvaLoading from 'dva-loading';
const app = dva({
history: BrowserHistory({
basename: 'erp',
}),
});
app.use(dvaLoading());
app.router(require('./router').default);
models
/models/list.js
export default {
namespace: 'list',
state: { tableData: [], chartData: []},
reducers: {},
effects: {
*asyncTable(action, effects) {},
*asyncChart(action, effects) {}
}
}
routes
@connect
@connect装饰器语法
@connect(
({list, loading}) => {
list,
tableLoading: loading.effects['list/asyncTable'],
chartLoading: loading.effects['list/asyncChart'],
}
)
class Card extends PureComponent {
render() {
const { tableLoading, chartLoading } = this.props;
return (
<div>
<Table loading={tableLoading} />
<Chart loading={chartLoading} />
</div>
)
}
}
connect
class Card extends PureComponent {
render() {
const { loading } = this.props;
const tableLoading = loading.effects['list/asyncTable'];
const chartLoading = loading.effects['list/asyncChart'];
const globalLoading = loading.global;
return (
<div>
<Table loading={tableLoading} />
<Chart loading={chartLoading} />
</div>
)
}
}
export default connect(({ list, loading }) => ({ list, loading }))(Card);