[MST] Build Forms with React to Edit mobx-state-tree Models
We will expand our UI, and give the user the possibility to edit his wishlist. We will use the earlier defined actions. We also will use model clones only to modify data temporarily, and after approving the changes, apply them back to the original model.
In this lesson you will learn:
- How to call model actions from a component
- Using
clone
to create a full, deep clone of any model instance - Using
applySnapshot
to update the state of a model instance given a snapshot.
The whole point for building a editing form component is that:
1. avoid two ways data flow, means that you change the data inside the form, without saving but the data was mutated already. To solve this problem, we will use 'clone' from 'mobx-state-tree'.
2. When save the data, we can use 'getSnapshot' and 'applySnapshot' from the lib.
import React, {Component} from "react" import {observer} from "mobx-react"; import {clone, getSnapshot, applySnapshot} from 'mobx-state-tree'; import WishListItemEdit from "./WishListItemEdit" class WishListItemView extends Component { constructor() { super(); this.state = {isEditing: false} } render() { const {item} = this.props; return this.state.isEditing ? this.renderEditable() : this.renderItemView(item); } renderEditable() { return ( <li className="item"> <WishListItemEdit item={this.state.clone}/> <button onClick={this.onSaveEdit}>💾</button> <button onClick={this.onCancelEdit}>❎</button> </li> ); } renderItemView(item) { return ( <li className="item"> {item.image && <img src={item.image}/>} <h3>{item.name}</h3> <span>{item.price}</span> <span> <button onClick={this.onToggleEdit}>✏</button> </span> </li> ); } onSaveEdit = () => { applySnapshot(this.props.item, getSnapshot(this.state.clone)) this.setState({ isEditing: false, clone: null }) }; onCancelEdit = () => { this.setState({isEditing: false}) }; onToggleEdit = () => { this.setState({ isEditing: true, clone: clone(this.props.item) }) } } export default observer(WishListItemView)
Here we have to use the methods provide from the lib, because the 'this.props.item' is a mobx state model object:
{$mobx: ObservableObjectAdministration, toString: ƒ, …}
The good part of this approach is that, the model related data can be handled by the mobx-state-tree lib. It can helps to udpate the model efficiently.
The down side of the approach is that, you needs to keep at least tow parts of state, one is mobx-state-tree, another one is the component state, for example, in the code, 'isEiditing' & 'clone'.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具