MENU

TypeScript 和 dva

• November 28, 2019 • Read: 4702 • Web Program

TS是大前端中非常重要的组成部分,实际开发中,让每个开发者拥有属于自己的模块,下面是对 dva ,Antd ProReact Hooks ,一些声明类型和坑的总结。 ⚠️ 值得注意的是 ,在Antd pro 内部 Model 自动映射到全局。

Hooks函数组件声明方式

interface IntrinsicElements {
    [elemName: string]: any;
}

使用

const Nodelist: React.FC<IntrinsicElements> =()=>{
            return (<h1>Hello,World!</h1>)
}
export default Nodelist;

Dva的声明

state

interface StateType {
    data:Array;
}

Effect

import { EffectsCommandMap, Model } from 'dva';
import { AnyAction, Reducer } from 'redux';
export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

整个Model的声明

import { EffectsCommandMap, Model } from 'dva';
import { AnyAction, Reducer } from 'redux';
export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;
interface StateType {
    data:Array;
}
interface ModelType {
    namespace: string;
    state: StateType;
    effects: {
        nodelists: Effect;
    };
    reducers: {
        save: Reducer<StateType>;
    };
}

此时 看看我实际整个Model层

import { getNodeList } from './service';
//初始状态
const defaultState: StateType = {
  data: [],
};
const Model: ModelType = {
  namespace: 'nodelist',
  state: defaultState,
  effects: {
    //List
    *nodelists({ callback }, { call, put }) {
      const response = yield call(getNodeList)
      let payload = { data: response.content.data }
      yield put({ type: 'save', payload });
    },
  },
  reducers: {
    save(state = { ...defaultState }, action) {
      return {
        ...state,
        ...action.payload
      };
    }
  },
};
//Link to dva warehouse Ts declaration type //这是给组件连接dva时声明类型用
export type AdminState = Readonly<typeof defaultState>;
//Export the nodelist module(automatically register to the global)
export default Model;

都是和我们定义好的 ModelType 一一对应的

看下Service层

import request from '@/utils/request';
//节点列表
export async function getNodeList() {
    return request('/admin/node', {
        method: 'GET'
    })
}

怎么Connect你的Model和Comment

首先建立一个叫connect.d.ts的连接文件

//链接dva仓库声明类型用
import { AdminState } from './model';

 interface ConnectState {
     nodelist: AdminState;//前面是你的命名空间 后面的是从我实际整个Model层 拿过来的Model类型
}

export default ConnectState;

Connect

/**
 * Connect is a built-in connector of dva.?️ ? 
 * The following is the fixed writing of the component link dva warehouse.
 * It contains the namespace you defined and the Loading object. 
 * It is worth noting that Loading is built into dva.Can be used directly.
 * Type Example loading: { effects: { [key: string]: boolean }.
 * It is worth remembering that you need to write your component name with a pair of parentheses at the end of the declared component.
 * This will connect your specified namespace repository (nodelist in this example) to the current component.
 * You can accept it component in props!
 * @author xiaohuwei 2019.11.27
 */
import React,{useEffect} from 'react';
import { Skeleton } from 'antd';
const Nodelist: React.FC<IntrinsicElements> =props=>{
     //这里接受仓库所有的方法 loading对象和触发器
      const { nodelist, dispatch, submitting } = props;
      useEffect(()=>{
            dispatch({type: 'nodelist/nodelists'})  //页面加载的时候调用dva的异步方法          
    },[])
            return (
        <>
             <Skeleton loading={submitting} active >
                    <h1>Hello,World!</h1>
                        </Skeleton>
        </>
      )
}
export default connect(
    ({ nodelist, loading }: { nodelist: ConnectState, loading: { effects: { [key: string]: boolean } } }) => //第一个值为你的仓库名 第二个为dva内置的loading对象 
    ({
    nodelist, 
    submitting: loading.effects['nodelist/nodelists'] || loading.effects['........'] //这里可以用 || 表示多个状态 哪个发请求 dva自动监听哪个请求状态 但是都可以用一个变量接收
    })
)(Nodelist)

⚠️ 值得注意的是: loading 对象是 dva 内置的,他会监听你指定的异步请求方法,方法开始的时候该值为 true ,异步方法结束了该值自动置为 false ,可用于页面刚进来时骨架屏的加载和某些需要 loading 状态的场景,当然 你可以在后面定义多个值(上面注释有说明),实现你当前组件的全局 loading 状态。在上面的代码中,页面刚加载的时候我们发了一个异步方法(nodelist 仓库下的异步 nodelists 方法),submitting 变为 true 骨架屏效果出现,这个方法执行完了(数据已经拿到)后submitting 会 变为 false