dva-loading Github https://github.com/dvajs/dva/tree/master/packages/dva-loading

  1. npm install dva-loading --save

loading

  • 异步加载方法的状态:异步加载中状态为 true,异步加载完成状态为 false
  • loading只针对 models里面的 effects里面的异步方法有效
  • 避免了异步自己手动的 setState loading

‘user/query’ 是个 effects里面,异步请求后台的方法

  1. loading: {
  2. global: true, // 全局的 loading,effect里面有一个 true,global就为 true
  3. effects: { 'user/query': true }, // 有哪些 effect在loading
  4. models: { 'user/query', true }, // 有哪些model在loading
  5. }

global

  1. 一个页面中,可能同时有多个异步加载,只要有一个异步加载没有完成,global 都是 true
  2. 但是 effects 中加载完成的,异步方法都会变成 false,只有没加载完成的异步方法才是 true
  3. 根据 loading.effects 对象判断当前 effects中的异步加载是否完成,并将该值传递给 组件的 props

loading.effects

异步请求中loading变量会为true,完成后会变成false

  1. // 监听某个模块下的所有异步请求
  2. const isLoading = loading.models.list;
  3. // 监听单个effect
  4. const isLoading = loading.effects['list/asyncTable']
  5. // 全局的 loading
  6. const globalLoading = loading.global;

loading.effects.png

index.js

/src/index.js

  1. import dva from 'dva';
  2. import { createBrowserHistory as BrowserHistory } from 'history';
  3. import dvaLoading from 'dva-loading';
  4. const app = dva({
  5. history: BrowserHistory({
  6. basename: 'erp',
  7. }),
  8. });
  9. app.use(dvaLoading());
  10. app.router(require('./router').default);

models

/models/list.js

  1. export default {
  2. namespace: 'list',
  3. state: { tableData: [], chartData: []},
  4. reducers: {},
  5. effects: {
  6. *asyncTable(action, effects) {},
  7. *asyncChart(action, effects) {}
  8. }
  9. }

routes

@connect

@connect装饰器语法

  1. @connect(
  2. ({list, loading}) => {
  3. list,
  4. tableLoading: loading.effects['list/asyncTable'],
  5. chartLoading: loading.effects['list/asyncChart'],
  6. }
  7. )
  8. class Card extends PureComponent {
  9. render() {
  10. const { tableLoading, chartLoading } = this.props;
  11. return (
  12. <div>
  13. <Table loading={tableLoading} />
  14. <Chart loading={chartLoading} />
  15. </div>
  16. )
  17. }
  18. }

connect

state.png

  1. class Card extends PureComponent {
  2. render() {
  3. const { loading } = this.props;
  4. const tableLoading = loading.effects['list/asyncTable'];
  5. const chartLoading = loading.effects['list/asyncChart'];
  6. const globalLoading = loading.global;
  7. return (
  8. <div>
  9. <Table loading={tableLoading} />
  10. <Chart loading={chartLoading} />
  11. </div>
  12. )
  13. }
  14. }
  15. export default connect(({ list, loading }) => ({ list, loading }))(Card);