umi 中内置了 Dva 插件,不用下载可以直接直接使用。
一、创建配置文件
umi项目中使用状态管理指南 (>_<)
- src目录下新建models文件,内部创建store.ts文件
// 这里是store.ts文件内部
import { Effect, Reducer } from 'umi';
export interface Option {
label: string;
value: string;
}
export interface storeState {
list?: Option[];
}
export interface ImmerAction {
type: string;
payload: {
immerType: string;
value: any;
};
[s: string]: any;
}
export interface storeType {
namespace: 'store';
state: storeState;
effects: {
//queryUserList: Effect;
};
reducers: {
//save: Reducer<AppState>;
//saveImmer: Reducer<AppState, ImmerAction>;
};
}
// 这里才是我们的主题👇🏻👇🏻👇🏻
const AppModel: storeType = {
namespace: 'store',
state: {
list: [],
},
effects: {
// 这里的东西一般情况下用不到。。。
},
reducers: {
setList: (state, action) => {
return {
...(state as any),
list: action?.payload,
};
},
}
}
export default AppModel;
- 在需要【传入】的项目中使用;
// 这里模拟 Axx.tsx 文件
import { useDispatch } from 'umi';
const Axx = (props: any) => {
const dispatch = useDispatch();
dispatch({ type: 'store/setList', payload: [1,2,3] });
return (......)
}
export default Axx;
- 在需要【展示/使用】的项目中使用;
// 这里模拟 Bxx.tsx 文件
import { useEffect } from 'react';
import { useSelector } from 'umi';
const Bxx = (props: any) => {
// 注意:playList不是一个函数;
const playList = useSelector((state: any) => {
return state.app.pageTableList;
});
useEffect(() => {
console.log(playList); // 打印结果:[1,2,3]
}, []);
return (......)
export default Bxx;