1、安装
cnpm install dva --save
2、创建model文件
其中这些文件会识别为model文件
src/models下的文件
src/pages/models下的文件
src/pages下所有model.ts文件
如在src/models/创建的文件
import {list} from '../service/dav'
export default{
namespace:'xx',
state:'x',
reducers:{},
effects:{}
}
3、与models同级创建service文件夹,用于创建api接口
4、组件连接model
import React,{Component} from 'react'
import {connect} from 'dva'
class App extends Component{
get=()=>{
const {dispatch}=this.props;
dispatch({
type:'davDemo/list',
payload:{
id:1
},
callback:res=>{
console.log('callback:'+res);
}
})
}
render()
{
const {davDemo}=this.props;
return(
<div>
dva
<Button onClick={this.get}>加载</Button>
</div>
)
}
}
const mapStateToProps=(state)=>{
return{
davDemo:state.davDemo
}
}
export default connect( mapStateToProps)(App)
5、使用Mock模拟数据
export default{
'GET /xx':x
}
网络请求去请求该路径即可
代码示例:
层级关系
model/dev.js:
import {list} from '../service/dav'
export default{
namespace:'davDemo',
state:{
list:[]
},
reducers:{
listInfo(state,action){
return {
...state,
list:action.payload
}
}
},
effects:{
*list({payload,callback},{put,call})
{
const res=yield call(list,payload);
yield put({
type:'listInfo',
payload:res
})
callback(res);
}
}
}
service/dav.js:
import axios from 'axios'
export async function list(params){
console.log('params:'+params);
const res=await axios.get('/api/index');
console.log(res.data);
return res;
}
组件:
import React,{Component} from 'react'
import {connect} from 'dva'
import {Button} from 'antd'
class App extends Component{
get=()=>{
const {dispatch}=this.props;
dispatch({
type:'davDemo/list',
payload:{
id:1
},
callback:res=>{
console.log('callback:'+res);
}
})
}
render()
{
const {davDemo}=this.props;
return(
<div>
dva
<Button onClick={this.get}>加载</Button>
</div>
)
}
}
const mapStateToProps=(state)=>{
return{
davDemo:state.davDemo
}
}
export default connect( mapStateToProps)(App)
mock/index.js:
export default{
'GET /api/index':[1,2,3,4]
}
.umirc.ts:
import { defineConfig } from 'umi';
export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
routes: [
{ path: '/', component: '@/pages/index', },
{ path: '/user', component: '@/pages/user/index',
routes:[{
path: '/user/child', component: '@/pages/user/child/index'
}]
},
{ path: '/dva', component: '@/pages/dva/index', },
],
});