看了一个阿里大佬写的文档,发现并没有描述的清楚,尤其是对react基础不熟的初学者来说,state的运用即可实现各种组件状态的控制。
昨天晚上写完一个查询表格,发现数据的加载需要一定时间,而表格未加载进数据时会呈现出暂无数据的尴尬状态,加一个loading
效果能更好地缓冲尴尬。
需要修改的地方有这处:
因为数据的载入我模仿的是前端有model层的方案,所以先给出这一个:
index.tsx
class ADUserPage extends Component {
componentDidMount() {
this.loadData(); // 加载数据
}
//获取AD域用户列表
loadData() {
console.log('页面方法 loadData');
//使用connect后,dispatch通过props传给了组件
const { dispatch } = this.props;
dispatch({ type: 'ad/fetchADUserList', payload: [] });
}
...
...
render() {
const { ad } = this.props;
const { ADUserList, loading } = ad;
...
...
}
return (
<PageHeaderWrapper>
<ProTable
headerTitle="AD域用户列表"
rowKey="sam"
columns={columns} // 列名
dataSource={ADUserList} // 数据源
search={true} // 搜索
scroll={{ x: 1300 }} // 滑动轴
pagination={true} // 分页
loading={loading} // 加载中
...
...
//使用umi的connect方法把命名空间为 visual 的 model 的数据通过 props 传给页面
export default connect(({ ad }) => ({ ad }))(ADUserPage);
models
import { fetchADUserList } from '@/services/ad';
import { message } from 'antd';
export default {
namespace: 'ad',
state: {
ADUserList: [],
loading: true, // 表格加载标记,初始化值为true
},
effects: {
*fetchADUserList({ payload }, { call, put }) {
console.log('model-effects-fetchADUserList');
const response = yield call(fetchADUserList, payload);
if (response.code === 0) {
yield put({
type: 'setUserList',
payload: response.body,
});
} else {
message.error(response.message);
yield put({
type: 'setUserList',
payload: [],
});
}
},
},
reducers: {
setUserList(state, action) {
return {
...state,
ADUserList: action.payload,
loading: false, // 表格加载标记,数据载入完毕设为false
};
},
},
};
浅显的总结:
只需要搜索loading字样就知道所有需要修改的地方了!
主要是在Model层发请求前将表格loading标记初始化为true,然后后端传过来数据后到reducers
这里时候将标记设置为false;
然后index页面用umi的connect将命名空间为 visual 的 model 的数据通过 props 传给页面,这里传给页面的数据就包含loading;
到目前为止,我对于props state 和reducers还不是很清楚,不过模仿写过index->model->service->后端url 流程的查询接口和index->service->后端url 忽略了model层的post接口