react desigin pro与服务器交互
程序员文章站
2022-06-07 12:18:17
...
在 Ant Design Pro 中,一个完整的前端 UI 交互到服务端处理流程是这样的:
- UI 组件交互操作;
- 调用 model 的 effect;
- 调用统一管理的 service 请求函数;
- 使用封装的 request.ts 发送请求;
- 获取服务端返回;
- 然后调用 reducer 改变 state;
- 更新 model。
直接上代码
data.d.ts
export interface ListItemData {
id: string;
name:string;
pid:string;
}
model.ts
import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { queryOrgList } from './service';
import { ListItemData } from './data.d';
export interface StateType {
list: ListItemData[];
}
export type Effect = (
action: AnyAction,
effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;
export interface ModelType {
namespace: string;
state: StateType;
effects: {
fetch: Effect;
};
reducers: {
queryList: Reducer<StateType>;
};
}
const Model: ModelType = {
namespace: 'modelList',
state: {
list: [],
},
effects: {
*fetch({ payload }, { call, put }) {
const response = yield call(queryOrgList, payload);
yield put({
type: 'queryList',
payload: Array.isArray(response) ? response : [],
});
},
},
reducers: {
queryList(state, action) {
return {
...state,
list: action.payload,
};
},
},
};
export default Model;
service.ts
import request from '@/utils/request';
import { ListItemData } from './data.d';
interface ParamsType extends Partial<ListItemData> {
count?: number;
}
export async function queryOrgList(params: ParamsType) {
return request('/api/org/list', {
params,
});
}
index.tsx
import React, { FC, useEffect } from 'react';
import { List,} from 'antd';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import { StateType } from './model';
import { ListItemData} from './data.d';
interface Props {
modelList: StateType;
dispatch: Dispatch<any>;
// loading: boolean;
}
const ListContent = ({
data: { id, name, pid },
}: {
data: ListItemData;
}) => (
<div >
<div>
<span>{id} --- {name} ---- {pid}</span>
</div>
</div>
);
export const BasicList: FC<Props> = props => {
const {
// loading,
dispatch,
modelList: { list },
} = props;
useEffect(() => {
dispatch({
type: 'modelList/fetch',
payload: {
count: 10,
},
});
}, [1]);
console.log({list});
return (
<div>
<List
size="large"
rowKey="id"
// loading={loading}
dataSource={list}
renderItem={item => (
<List.Item>
<ListContent data={item} />
</List.Item>
)}
/>
</div>
);
};
export default connect(
({
modelList,
// loading,
}: {
modelList: StateType;
// loading: {
// models: { [key: string]: boolean };
// };
}) => ({
modelList,
// loading: loading.models.modelList,
}),
)(BasicList);
代码比较简洁
上一篇: 玫瑰花茶减肥吗?答案全在这里了!
下一篇: Java-对系统时间进行的操作