本文共 2864 字,大约阅读时间需要 9 分钟。
注明一下:
我用的 antd pro 脚手架是 2.0 版本的
。
在讲 mock 之前,默认你已经掌握: 新建页面、路由等基础功能。
这里用 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 (); }}export default Home;
由上面的 columns
可以看出,表格有三列,所以需要 mock
的数据有:name
, age
, address
, 当然还需要一个key
这是 React
需要额外添加的。
如图:在mock 文件夹
下的API 文件
里,写入一些mock 数据
,并在 /api/home
这个接口模拟出来
在 services 文件夹
下的API 文件
中写一个请求/api/home
端口数据的函数 queryhome
。
这些代码的作用就是接收 action,更新 state 并传递给 props,怎么接收 action
后面会提到。而更新 state
,就是上面的 show
方法啦,然后这里的 state.list
就会被发送给 props
。可以看到原来定义的发送请求的函数queryHome
被 import
进来,然后在fetch
函数中调用,所以,只要调用fetch
函数,就会请求mock
数据。
如果项目开发完毕,需要发送到线上,只需把请求的数据接口(上述的 /api/home
)换成真实的即可。
下面代码仅用于方便读者复制使用:
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, }; }, },};
在组件文件中:
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(命名空间)。
const dataSource = [...list];return ();
页面渲染如下:
到此为止,数据请求成功!!!
组件中的完整代码如下:
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 { 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 (); }}export default Home;
有错误或不足,欢迎评论指正~
以上 ?