dva-loading 使用详解

本文详细介绍了如何使用 dva-loading 实现页面加载状态管理。首先,介绍了安装和引入 dva-loading 的步骤,然后讲解了如何在 reducer 中添加 loading 属性,并在组件中获取和使用该属性来跟踪异步请求状态。通过具体示例,包括 model 代码和使用 loading 属性的组件,展示了如何利用 loading.effects 监测特定异步操作的 loading 状态。

前言

日常积累,欢迎指正

1、安装依赖

yarn add dva-loading
# or
npm install dev-loading

2、dva-loading 引入

import createLoading from 'dva-loading'
app.use(createLoading())

3、dva-loading 使用 - 利用 dva-loading 实现 loading

3.1、使用 app.use(createLoading()) 之后 reducer 的 state 中会增加一个 loading 属性

3.2、在需要使用 loading 的组件中获取到它

我这里是通过容器组件中将这个 loading 属性传递给需要使用它的组件中的


function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    loading:state.loading
  }
}

3.3、组件拿到 loading 属性后通过它可以检测指定的异步请求的状态以此来判断对应组件的 loading 状态

这里以异步请求 addAsync 为例

3.3.1、model 代码
import { listStatus,actionType } from '../constants/todoList'
import { asyncAdd } from '../services/todoList'
export const todoList = 'todoList'
export default {
  namespace: todoList,
  reducers: {
    ADD(state, action) {
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          status: action.status
        }
      ]
    }
  },
  effects: {
    *addAsync(action, effects) {
      const result = yield effects.call(asyncAdd, action.text)
      // console.log(result)
      yield effects.put({
        type:`${todoList}/ADD`,
        id: action.id,
        text: result,
        status: action.status
      })
    }
  }
};
3.3.2、需要使用 loading 属性的组件
import { Spin } from 'antd'
export default class TodoList extends React.Component {
  render() {
    const loading = this.props.loading.effects['todoList/addAsync']
    return (
      <Spin spinning={!!loading}>
        <div>
          <h1>todoList</h1>
        </div>
      </Spin>
    )
  }
}

注意点: loading.effects['todoList/addAsync'] 的 key 值

这里 loading.effects[‘todoList/addAsync’] 就会拿到 namespace 为 ‘todoList’ 的 model 中的名称为 addAsync 的异步请求的状态(true/false),当指定的异步请求不存在就会返回 undefined

4、示例源码

dvaLearning

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值