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>;
};
subscriptions: { setup: Subscription };
}
const IndexModel: IndexModelType = {
namespace: 'index',
state: {
name: 'index',
},
effects: {
*query({ payload }, { call, put }) {
yield put({type:'save',payload})
},
},
reducers: {
save(state, action) {
return {
...state,
...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 }) => {
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);
},[])
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()},[])