- MobX Quick Start Guide
- Pavan Podila Michel Weststrate
- 297字
- 2021-08-05 10:34:25
A reactive UI
On the topic of reactions, it is worth mentioning that the UI is one of the most glorious reactions (or side-effect) you can have in an app. As we saw in the earlier chapter, UI depends on data and applies a transformation function to generate the visual representation. In the MobX world, this UI is also reactive, in the sense that it reacts to the changes in data and automatically re-renders itself.
MobX provides a companion library called mobx-react that has bindings to React. By using a decorator function (observer()) from mobx-react, you can transform a react component to observe the observables used in the render() function. When they change, a re-render of the react component is triggered. Internally, observer() creates a wrapper component that uses a plain reaction() to watch the observables and re-render as a side-effect. This is why we treat UI as being just another side-effect, albeit a very visible and obvious one.
A short example of using observer() is shown next. We are using a stateless functional component, which we are passing to the observer. Since we are reading the item observable, the component will now react to changes in item. After two seconds, when we update item, the ItemComponent will automatically re-render. Take a look at this:
import { observer } from 'mobx-react';
import { observable } from 'mobx';
import ReactDOM from 'react-dom';
import React from 'react';
const item = observable.box(30);
// 1. Create the component with observer
const ItemComponent = observer(() => {
// 2. Read an observable: item
return <h1>Current Item Value = {item.get()}</h1>;
});
ReactDOM.render(<ItemComponent />, document.getElementById('root'));
// 3. Update item
setTimeout(() => item.set(50), 2000);
We will cover mobx-react in Chapter 3, A React App with MobX, and also throughout this book.
- 社交網(wǎng)絡(luò)對齊
- Aptana Studio Beginner's Guide
- Modern JavaScript Web Development Cookbook
- HCNA網(wǎng)絡(luò)技術(shù)
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- 信息通信網(wǎng)絡(luò)建設(shè)安全管理概要2
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- 企業(yè)網(wǎng)絡(luò)安全管理
- Mastering TypeScript 3
- 物聯(lián)網(wǎng)通信技術(shù)
- 網(wǎng)絡(luò)安全應(yīng)急響應(yīng)技術(shù)實戰(zhàn)
- 語音信號處理及Blackfin DSP實現(xiàn)
- 網(wǎng)絡(luò)空間全球治理觀察
- Dart Cookbook
- Web用戶查詢?nèi)罩就诰蚺c應(yīng)用