umi dva demo

model

import {routerRedux} from 'dva/router'
//routerRedux实现在effcts中路由跳转
export default {
  namespace:"user",
  state:{
    userInfo:{
      name:"name0",
      age:"0"
    }
  },
  subscription:{},
  effects:{
    * getUserInfo({payload},{call,put}){
      debugger;
          yield put({
            type:"changeState",
            payload:{
              userInfo:{
                name:"name1",
                age:"1"
              }

            }
          })
    },
    * changeRouter({payload},{call,put}){
      yield put({
        type:"changeState",
        payload:{
          userInfo:{
            name:"name1",
            age:"1"
          }

        }
      })
    }
  },
  reducers:{
    changeState(state,action){
        return {...state,...action.payload}
    }
  }
}

使用model与view关联

import React from 'react'
import {Button} from 'antd'
import {useDispatch,useSelector} from 'dva'
let Login = ({props})=>{
  let userInfo = useSelector(state => state.user.userInfo);
  let dispatch = useDispatch();
   let changeUserInfo = () => {
     dispatch(
       {
          type:"user/getUserInfo",
          payload:{

          }
       }
     )
   }
    return (<div>
      <Button onClick={changeUserInfo}>修改用户信息</Button>
      <p>
        登录
        {userInfo.name}
        {userInfo.age}
      </p>
    </div>)
}

export default Login;

model与view关联方式

1 注解connect (@connect)

function mapStateToProps(state) {
  return { userInfos: state.userInfos};
}

2 react-hooks

let dispatch = userDispatch(),

let userInfo = userSelect(state => state.modeNamespace.info)

dispatch({
  type: 'user/getUserInfo', // 如果在 model 外调用,需要添加 namespace
  payload: {}, // 需要传递的信息
});
上一篇:umi 样式隔离


下一篇:umi-request 网络请求之路