dva插件学习笔记

dva插件

通过dva对象.use(插件),来使用插件,插件本质上就是一个对象,该对象与配置对象相同,dva会在启动时,将传递的插件对象混合到配置中。

dva-loading

该插件会在仓库中加入一个状态,名称为loading,它是一个对象,其中有以下属性

  • global:全局是否正在处理副作用(加载),只要有任何一个模型在处理副作用,则该属性为true
  • models:一个对象,对象中的属性名以及属性的值,表示哪个对应的模型是否在处理副作用中(加载中)
  • effects:一个对象,对象中的属性名以及属性的值,表示是哪个action触发了副作用

实例,点击按钮对state仓库中的counter属性进行加、减操作

全局indexjs文件引入dva-loading插件

import routerConfig from "./routerConfig"
import dva from "dva";
import counterModel from "./models/counter"
import studentsModel from "./models/students"
import { createBrowserHistory } from "history"
import createLoading from "dva-loading"

//得到一个dva对象
const app = dva({
    history: createBrowserHistory()
});

app.use(createLoading()); //使用dva-loading插件

//在启动之前定义模型
app.model(counterModel)
app.model(studentsModel)

//设置根路由,即启动后,要运行的函数,函数的返回结果会被渲染
app.router(routerConfig)

app.start("#root")

counter组件,点击相应操作并于dva-loading结合

import React, { useRef } from 'react'
import { connect } from "dva"
import Modal from "./components/common/Modal"

function Counter(props) {
    const inp = useRef();
    return (
        <div>
            <h1>{props.number}</h1>
            <button onClick={props.onAsyncDecrease}>异步减</button>
            <button onClick={props.onDecrease}> - </button>
            <button onClick={props.onIncrease}> + </button>
            <button onClick={props.onAsyncIncrease}>异步加</button>
            <p>
                <input type="number" ref={inp} />
                <button onClick={() => {
                    const n = parseInt(inp.current.value);
                    props.onAdd(n);
                }}>加上</button>
            </p>
            {
                props.isLoading && <Modal>
                    <div style={{ color: "#fff", fontSize: "2em" }}>
                        加载中....
                    </div>
                </Modal>
            }
        </div>
    )
}

const mapStateToProps = state => ({
    number: state.counter,
    isLoading: state.loading.models.counter
})

const mapDispatchToProps = dispatch => ({
    onIncrease() {
        dispatch({
            type: "counter/increase"
        })
    },
    onDecrease() {
        dispatch({
            type: "counter/decrease"
        })
    },
    onAdd(n) {
        dispatch({ type: "counter/add", payload: n })
    },
    onAsyncIncrease() {
        dispatch({ type: "counter/asyncIncrease" })
    },
    onAsyncDecrease() {
        dispatch({ type: "counter/asyncDecrease" })
    }
})

export default connect(mapStateToProps, mapDispatchToProps)(Counter)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值