今天肺炎增长数字依然吓人,感觉穿越到丧失片里了。

本节开始学习dva model使用,官网的讲解太文档化,对新手实践不太友好,自己简化了一个最简单的演示代码。

1、在src,models文件夹下创建user.ts,初始化username为张三1

const UserModel = {
namespace: 'User',
state:{
UserInfo:{
username:"张三1"
}
},
reducers:{
updateUserState(state,action)
{
let currentUser=state.UserInfo;
console.log("CurrentUser:"+currentUser);
console.log(currentUser);
console.log("CurrentUserPayload:")
console.log(action.payload.UserInfo);
state=action.payload;
return state;
}
}
};
export default UserModel;

注意:

红色部分如果写成

state.UserInfo.username=action.payload.UserInfo.username;
不会自动刷新
 
要写成
state=action.payload;
 
或者后两句写为
return { ...state,UserInfo:action.payload.UserInfo} 
 
因为必须返回一个新的引用才会更新页面

2、修改user.tsx如下

import React from 'react';
import { Button,Input} from 'antd';
import {connect} from 'dva'; class User extends React.Component {
render() {
console.log("render:");
console.log(this.props);
return (
<div>用户管理
<div>姓名:{this.props.UserInfo.username}</div>
<Button type="primary" style={{marginTop:10,width:300}} onClick={this.handleClick}>修改</Button>
</div>
);
}
handleClick = e => {
const userInfo={
UserInfo:{
username:"张三2"
}
}
this.props.dispatch({
type:"User/updateUserState",
payload:userInfo
})
console.log('click: ', e);
};
}
const getUserInfoFromState=(state)=>{
console.log(state);
return {UserInfo:state.User.UserInfo} }
export default connect(getUserInfoFromState)(User) ;

3、运行效果如下
AntDesign(React)学习-9 Dva model reducer实践-LMLPHP

4、点击修改后

AntDesign(React)学习-9 Dva model reducer实践-LMLPHP

5、console日志如下
AntDesign(React)学习-9 Dva model reducer实践-LMLPHP

05-25 15:38