一、mobx简介
MobX 是一个经过战火洗礼的库,它通过透明的函数响应式编程(transparently applying functional reactive programming - TFRP)使得状态管理变得简单和可扩展。MobX背后的哲学很简单:任何源自应用状态的东西都应该自动地获得。其中包括UI、数据序列化、服务器通讯,等等。
React 和 MobX 是一对强力组合。React 通过提供机制把应用状态转换为可渲染组件树并对其进行渲染。而MobX提供机制来存储和更新应用状态供 React 使用。
二、Core concepts
1、State。
MobX adds observable capabilities to existing data structures like objects, arrays and class instances. This can simply be done by annotating your class properties with the@observabledecorator (ES.Next).These values are the “data cells” of your application.
2、Derivations
Secondly there are derivations. Basically, any value that can be computed automatically from the state of your application. These derivations, or computed values, can range from simple values, like the number of unfinished todos, to complex stuff like a visual HTML representation of your todos. In spreadsheet terms: these are the formulas and charts of your application.
3、Reactions
Reactions are very similar to derivations. The main difference is these functions don't produce a value. Instead, they run automatically to perform some task. Usually this is I/O related. They make sure that the DOM is updated or that network requests are made automatically at the right time.
4、Actions
Finally there are actions. Actions are all the things that alter the state. MobX will make sure that all changes to the application state caused by your actions are automatically processed by all derivations and reactions. Synchronously and glitch-free.
三、demo及代码演示
1、todo list demo
2、定义todo 数据模型
3、定义todo list 数据模型
4、设计todo组件
5、设计todo list组件
6、渲染todo list
四、Conclusion
1、Use the @observable decorator or observable(object or array) functions to make objects trackable for MobX.
2、The @computed decorator can be used to create functions that can automatically derive their value from the state.
3、Use autorun to automatically run functions that depend on some observable state. This is useful for logging, making network requests, etc.
4、Use the @observer decorator from the mobx-react package to make your React components truly reactive. They will update automatically and efficiently. Even when used in large complex applications with large amounts of data.
参考资源:
1、Mobx:https://mobx.js.org/index.html
2、Ten minute introduction to MobX and React
:https://mobx.js.org/getting-started.html
领取专属 10元无门槛券
私享最新 技术干货