官网链接
文件目录
page 页面
index.tsx
models 每一个model文件都是需要挂在dva实例上的才会生效
demo.ts
sevices 写接口的(这里就不写了)
demo.ts
实现一个简单的数据流向,将数据存储到dva,然后在页面使用
import { connect } from 'umi';
import { useEffect } from 'react';
import { Dispatch, Action } from 'redux';
interface demoProps {
dispatch: Dispatch<Action<
| 'Demo/addCount'
>>
}
const View = (props:demoProps)=>{
useEffect(()=>{
let {count} = props.Demo
props.dispatch({
type:'Demo/addCount',
payload:{count,count++}
callback(){
//获取回调的地方,如果需要操作返回的新数据
}
})
},[])
return(
<h1>{props.Demo.count}<h1>
)
}
connect(
({Demo})=>{
return Demo
},
(dispatch)=>{
return {dispatch}
}
)(View)
import { Effect } from 'dva';
import { Reducer } from 'redux';
interface DemoStateType{
count: number,
}
interface DemoType{
namespace: string,
state: DemoStateType,
effects:{
addCount: Effect,
}
reducer:{
setDemoState: Reducer
}
}
export default Demo: Demotype{
namespace:'Demo',
state: {
count: 0,
},
effects: {
*addCount: ({payload,callback}{put,call,select})=>{
//payload 接收到的数据
//callback 将数据返回页面
//put 用于调用reducer
//call 用于调用seveice文件里的接口
//select 可以获取所有模块中存储的值
put({
type:'setDemoState',
playload
})
}
},
reducer: {
setDemoState(state,{payload}){
return {
...state,
...payload
}
}
},
subscriptions:{ //这里并没有使用
setup({ dispatch, history }) {
// 这里可以用return
<!-- 这里是整个model文件第一个执行的地方 -->
//return history.listen((location, action) => {
// if (location.pathname === '/users') {
// dispatch({
// type是用来写effects的函数名
// type: 'effects_fnName'
// });
}
})
}
}
}
}