我尝试用react-native,mobx,mobx-state-tree创建一个User
模型
我的User
模型:
const UserProfileModel = types.model("UserProfile").props({
description: types.maybeNull(types.string),
})
/**
* Model description here for TypeScript hints.
*/
export const UserModel = types
.model("User")
.props({
created_at: types.optional(types.string, ""),
email: types.optional(types.string, ""),
first_name: types.optional(types.string, ""),
id: types.optional(types.string, ""),
last_name: types.optional(types.string, ""),
nick_name: types.maybeNull(types.string),
updated_at: types.optional(types.string, ""),
// @ts-ignore
profile: types.optional(UserProfileModel, {}),
})
.actions((self: any) => ({
updateNickName(nick_name: string): void {
self.nick_name = nick_name
}
}))
以及调用updateNickName
动作的班级:
@inject("userModel")
@observer
export class EditMyProfileScreen extends React.Component {
@observable private readonly userProfile: IUser = {} as IUser
constructor(props) {
super(props)
this.userProfile = clone(props.userModel)
}
@autobind
private async sendUpdateToServer(): Promise<void> {
const { userModel } = this.props
// do some async request to the server
userModel.updateNickName(this.userProfile.nick_name)
console.log(userModel) // this console.log print an old version of the javascript object
}
render() {
// do stuff
}
}
但是在调用userModel.updateNickName
之后,似乎没有更新用户。
为什么nick_name
字段未更新?
答案 0 :(得分:0)
升级到mobx-state-tree
v3.15.0 后,该问题似乎已解决。