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<IndexModelState>;
  };
  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进行开发时,函数式组件主要负责视图的渲染和展示,而状态管理则常常通过外部的状态管理库来实现,比如umi/dva。在umi/dva框架中,model文件用于定义状态和对应的reducer以及effects,它其实就是一个状态容器。 要将函数式组件与umi/dva中的model文件联系起来,通常有以下几种方式: 1. connect函数:umi/dva提供了connect函数,用于连接React组件与dva model。你可以通过connect函数将model中的state和dispatch方法映射到组件的props上。这样,函数式组件就可以读取model中定义的状态,并能够通过调用dispatch方法来触发状态的更新。 ```jsx import { connect } from 'dva'; function MyComponent({ count }) { // 使用count状态 return <div>{count}</div>; } // 将model的state映射到MyComponent的props上 export default connect(state => ({ count: state.count }))(MyComponent); ``` 2. Hooks API:在dva v3及以上版本,提供了useModelState、useModelState、useAction等自定义Hooks,使得函数式组件可以更直接地与model进行交互,而无需使用connect进行映射。 ```jsx import { useModelState } from 'dva'; function MyComponent() { // 直接使用useModelState获取状态 const count = useModelState('count'); return <div>{count}</div>; } ``` 3. 使用withModel高阶组件:在不使用connect的情况下,可以通过withModel这样的高阶组件来包装你的函数式组件,使其能够获取到model中的状态和操作。 ```jsx import withModel from 'dva/withModel'; function MyComponent({ count }) { // 使用count状态 return <div>{count}</div>; } export default withModel(MyComponent); ``` 这些方法将函数式组件与umi/dva中的model文件紧密联系起来,使得组件能够响应状态的变化并进行相应的更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值