umi插件(dva/model)使用

dva

创建model

import { Effect, Reducer, Subscription } from 'umi';

export interface IndexModelState {
  name: string;
}

export interface IndexModelType {
  namespace: 'index';
  state: IndexModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    save: Reducer<IndexModelState>;
    // 启用 immer 之后
    // save: ImmerReducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'index',

  state: {//状态
    name: 'index',
  },

  effects: {//使用call调用异步方法 put调用reducers
    *query({ payload }, { call, put }) {
       yield put({type:'save',payload})
    },
  },
  reducers: {//操作state
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {//订阅
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/testDva') {
          dispatch({
            type: 'query',
            payload:{name:"張三"}
          });
        }
      });
    },
  },
};

export default IndexModel;

链接组件

import React, { FC, useEffect } from 'react';
import { IndexModelState, ConnectProps, Loading, connect, Dispatch } from 'umi';

interface PageProps extends ConnectProps {
  index: IndexModelState;
  loading: boolean;
  dispath:Dispatch;
}

const IndexPage: FC<PageProps> = ({ index, dispatch }) => {
    // 调用model方法例子
    // useEffect(()=>{
    //    dispatch(
    //        {
    //            type:"index/query",
    //            payload:{name:'HHHH'},
    //         }
    //         )
    // },[])
  const { name } = index;
  return <div>Hello {name}</div>;
};

export default connect(
  ({ index, loading }: { index: IndexModelState; loading: Loading }) => ({
    index,
    loading: loading.models.index,
  }),
)(IndexPage);

model


import moment from 'moment';
import { useState, useCallback } from 'react'

export default function tableModel(){
 const [tableList,setTableList] = useState<any[]>([]);

 /**
  * 查詢
  * 
  */
 const queryList = useCallback((name?:string)=>{
     let tableListDataSource = []
    for (let i = 0; i < 10; i += 1) {
        const index = (1 - 1) * 10 + i;
        tableListDataSource.push({
          key: index,
          disabled: i % 6 === 0,
          href: 'https://ant.design',
          avatar: [
            'https://gw.alipayobjects.com/zos/rmsportal/eeHMaZBwmTvLdIwMfBpg.png',
            'https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png',
          ][i % 2],
          name: `TradeCode ${index}`,
          owner: '曲丽丽',
          desc: '这是一段描述',
          callNo: Math.floor(Math.random() * 1000),
          status: Math.floor(Math.random() * 10) % 4,
          updatedAt: moment().format('YYYY-MM-DD'),
          createdAt: moment().format('YYYY-MM-DD'),
          progress: Math.ceil(Math.random() * 100),
        });
      }
      tableListDataSource.reverse();
      console.log(tableListDataSource)
    setTableList(tableListDataSource);
 },[])

 /**
  * 刪除
  * @param name 姓名
  */
 const deleteList = useCallback((name?:string)=>{

    setTableList(tableList.filter((e)=>e.name != name));
 },[])

 const insertList = useCallback((obj?:any)=>{

    setTableList([...tableList,obj]);
 },[])

 const updateList = useCallback((name?:string)=>{

    setTableList([]);
 },[])

 return{
     tableList,
     queryList,
     deleteList,
     insertList,
     updateList
 }
}

组件使用

const {tableList,queryList,deleteList,insertList,updateList} = useModel('TableList.table')

  useEffect(()=>{queryList()},[])

你可能感兴趣的:(前端,react.js,javascript,typescript)