版权声明:本文为博主原创文章,转载请注明原文出处。 https://blog.csdn.net/qq_41139830/article/details/82976282
说明一下:我用的antd pro脚手架是2.0版本的
。
说mock之前默认新建页面,路由等基础功能你已经掌握。
1、页面需要什么格式的数据
我用一个antd pro
里面的表格组件
作为演示:
import { Table } from 'antd';
class Home extends Component {
render() {
const columns = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
}, {
title: 'Age',
dataIndex: 'age',
key: 'age',
}, {
title: 'Address',
dataIndex: 'address',
key: 'address',
}];
return (
<div>
<Table
bordered
dataSource={dataSource}
columns={columns}
size="small" />
</div>
);
}
}
export default Home;
上面就用antd pro框架
新建了一个最简单的表格,由上面配置表格头部的columns
可以看出,需要mock
的数据有:name
, age
, address
, 当然还需要一个key
这是另外要加的。
2、准备mock数据
如图:在mock文件夹
下的api文件
里,写入一些mock数据
,并在/api/home
这个接口模拟出来
3、发送请求
在services文件夹
下的api文件
中写一个请求/api/home端口
数据的函数queryhome
。
4、建立我们自己的model,来接收action,更新state并传递给props
这些代码的作用就是接收action,更新state并传递给props
,怎么接受action
后面会提到,更新state
,就是上面的show方法
啦,然后这里的state.list
就会被发送给props
。可以看到原来定义的发送请求的函数queryHome
被导入了进来,然后在fetch函数
中调用,所以,只要调用fetch函数
,就会请求mock数据
。
下面代码仅用于方便读者复制使用:
import { queryHome } from '@/services/api';
export default {
namespace: 'home',
state: {
list: [],
},
effects: {
*fetch({ payload }, { call, put }) {
const response = yield call(queryHome, payload);
yield put({
type: 'show',
payload: response,
});
},
},
reducers: {
show(state, action) {
return {
...state,
list: action.payload,
};
},
},
};
5、请求数据
在组件文件中:
import { connect } from 'dva';
@connect(({ home, loading }) => ({ //连接home.js文件
home,
loading: loading.models.home,
}))
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'home/fetch', //action的类型,由home命名空间和其下面的fetch方法构成
}); //派发这个action就会调用home中的fetch函数,然后就会请求数据
}
const { home: { list } } = this.props; //将home中的this.props.list命名为list
这个文件里home
是前面home.js文件
中的namespace: ‘home
’(命名空间)。
6、使用
const dataSource = [...list];
return (
<div>
<Table
bordered
dataSource={dataSource}
columns={columns}
size="small" />
</div>
);
页面渲染如下:
到此为止,数据请求成功!!!
组件中的完整代码是:
import React, { Component } from 'react';
import { connect } from 'dva';
import { Table } from 'antd';
@connect(({ home, loading }) => ({
home,
loading: loading.models.home,
}))
class Home extends Component {
constructor(props) {
super(props);
this.state = {
dataList: [],
};
}
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'home/fetch',
});
}
render() {
const columns = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
}, {
title: 'Age',
dataIndex: 'age',
key: 'age',
}, {
title: 'Address',
dataIndex: 'address',
key: 'address',
}];
const { home: { list } } = this.props;
const dataSource = [...list];
return (
<div>
<Table
bordered
dataSource={dataSource}
columns={columns}
size="small" />
</div>
);
}
}
export default Home;
参考链接:https://blog.csdn.net/xian_kaibite/article/details/80161790
有错误或不足,欢迎评论指正~
END!