react使用dva对数据做GET或POST请求
首先在组件页面 中添加
componentDidMount(){
const { dispatch } =this.props;
dispatch({
//type里的menu是models/里面的命名空间namespace的menu
type:'menu/fetchMenus',
payload:{},
callback:res=>{
console.log(res,111);
},
});
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
//接下来在models/ (意思是在models文件下创建一个model的组件)
import * as API from '../services/api';
export default {
namespace:'menu',
state:{
menu:[],
},
effects:{
//fetchMenus给到services/apis/的
*fetchMenus({callback},{call ,put}){
const response =yield call(API.fetchMenus);
yield put({
//public是写在下面reducers里,携带的参数是固定的(也就是修改数据)
type:'public',
payload:{...response, name:'menu'},
});
if(response.code===0){
if(callback) callback(response.data);
}
},
},
reducers:{
public(state, action){
return{
...state,
[action.payload.name]:action.payload.data,
}
},
clearData(){
return{
menu:[],
}
},
},
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
然后在services/apis/(意思是在services/apis文件下再创建一个)
// 模拟 GET请求
import { v1, checkCode } from '../config';
import request from '../../utils/request';
export async function fetchMenus() {
const response = request(`${v1}/users/821/menus`);
return checkCode(response);
};
//模拟 POST请求
//
import { v1, checkCode } from '../config';
import request from '../../utils/request';
import { getUserId } from '../../utils/token';
// 只有这里发生变化,在后面有传值
export async function Banksd(params) {
const id = getUserId();
const response =request(`${v1}/users/${id}/current`,{
mtehod:'POST',
body:params,
})
return checkCode(response);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
接下来在services/去请求apis下创建接口组件的路径
export * from './apis/menus';
- 1
最后在路由 common/router.js 里对应的组件页面路由写入模块组件名
'/wechat/department': {
identity: 'common',
//['menus']就是models下的menu
component: dynamicWrapper(app, ['menus'], () => import('../routes/Wechat/Department')),
},
- 1
- 2
- 3
- 4
- 5
结果如下