umi + ts 配合使用 dva model
import { connect } from 'umi' 生效条件
1. model文件需放置在 src/models下
2. umi会识别符合条件的models文件
开启dva: .umirc.ts中配置
export default defineConfig({
...,
dva: { // 配置自己需要的设置即可
immer: true,
hmr: true,
},
});
model文件:src/models/shop.ts
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
const namespace = 'shop'
export const namespace_shop = namespace
interface ModelState {
name: string;
}
interface ModelsType {
namespace: typeof namespace;
state: ModelState;
effects: {
query: Effect;
};
reducers: {
save: Reducer<ModelState>;
// 启用 immer 之后
// save: ImmerReducer<IndexModelState>;
};
subscriptions: { setup: Subscription };
}
const ShopModels: ModelsType = {
namespace,
state: {
name: 'shop',
},
effects: {
*query({ payload }, { call, put }) {
yield put({
type: 'save',
payload: { name: '慧慧' }
})
},
},
reducers: {
save(state, action) {
return {
...state,
...action.payload,
};
},
},
subscriptions: {
setup({ dispatch, history }) {
return history.listen(({ pathname }) => {
if (pathname === '/shop') {
dispatch({
type: 'query',
})
}
});
}
}
};
export default ShopModels;
页面page文件:index.ts
import React, { Component, FC } from 'react';
import { connect, Dispatch, ConnectProps, namespace_shop} from 'umi';
const MODELS_NAME = namespace_shop
interface PageProps extends ConnectProps {
name: string;
loading: boolean;
dispatch: Dispatch
}
interface PageSate {}
class IndexPage extends Component <PageProps, PageSate> {
handleChangeName = () => {
this.props.dispatch({
type: `${MODELS_NAME}/save`,
payload: {
name: 'hahahha'
}
})
}
render() {
const { name = '' } = this.props
return <div onClick={() => this.handleChangeName()} >Hello {name}</div>;
}
}
const mapState = (state: any) => {
return {
...state[MODELS_NAME],
loading: state.loading.models[MODELS_NAME]
}
}
export default connect(mapState)(IndexPage);