1、在根目录下的.roadhogrc.mock.js文件中写好数据
module.exports = {
"POST /api/demo": (req, res) => {
setTimeout(() => {
res.json({
code: 0,
data: [{
id: 1,
name: '西瓜',
price: 5.1,
}, {
id: 2,
name: '苹果',
price: 6.2,
}, {
id: 3,
name: '香蕉',
price: 7.3,
}, {
id: 4,
name: '桃子',
price: 8.4,
}],
msg: "嘿嘿",
})
}, 300)
},
};
2、在需要渲染的页面的api.js文件里
import { post } from '../../../utils/request';
export const getList = (param = {}) => post('/api/demo', param);
3、在需要渲染的页面的model.js文件里
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import * as Api from './api';
export default {
namespace: 'goodsList',
state: {
list: [],
},
reducers: {
save(state, { payload }) {
return { ...state, ...payload };
},
saveList(state, { payload }) {
return {
...state,
list: payload,
};
},
},
effects: {
*getList({ payload }, { call, put }) {
// 请求前,根据实际需求确定是否需要显示loading
message.loading();
const { code, msg, data } = yield call(Api.getList, payload);
// 判断code做出相应的操作
// console.log(data);
if (code != 0) {
// 请求出错,根据实际需求确定是否需要明确提示用户
message.error(msg || '请求出错,请稍后再试~', 3);
// 请求数据出错,应当清空旧数据
yield put({
type: 'saveList',
payload: [],
});
return;
}
// 如果之前有调用loading,请求结束则销毁掉loading
message.destroy();
yield put({
type: 'saveList',
payload: data || [],
});
},
*getDetail({payload}, {call, put}) {
const { code, data = {} } = yield call(Api.getDetail, payload);
if (code != 0) {
// 请求出错,根据实际需求确定是否需要明确提示用户
message.error(msg || '请求出错,请稍后再试~', 3);
// 请求数据出错,应当清空旧数据
yield put({
type: 'saveList',
payload: [],
});
return;
}
message.destroy();
yield put(routerRedux.push('/detail',{name: 'dkvirus', age: 20}));
},
},
};
4、在在需要渲染的页面的List.jsx文件里
import React from 'react';
import { connect } from 'dva';
import cn from 'classnames';
import { Button, Table } from 'antd';
import './style.less';
class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'goodsList/getList',
payload: {},
}).then(() => {
console.log('数据加载完毕');
});
}
getColumns = () => {
return [{
title: '序号',
dataIndex: 'id',
key: 'id',
}, {
title: '名字',
dataIndex: 'name',
key: 'name',
}, {
title: '价格',
dataIndex: 'price',
key: 'price',
}];
}
render() {
const {list} = this.props;
return (
演示class
这里是goods模块的list页面
);
}
}
function mapState(state) {
const { goodsList = {} } = state;
return {
...goodsList,
};
}
export default connect(mapState)(Widget);