At the beginning of mobx experience
Since mobx is used in the technology stack of the company, I have never used mobx before. Today, I read through the MOBx document and made a summary.
mobx 5
Create a repository:
import { observable, computed, action, runInAction } from 'mobx';
class Store {
@observable todo = [
{ id: 0.name: 'x' },
{ id: 1.name: 'y' },
{ id: 2.name: 'z'}]; @computedget todo2() {
return todo.map(item= > item.id * 2);
}
// General synchronization
@action addTodo(item) {
let cpTodo = [...this.todo];
cpTodo.push(item);
this.todo = cpTodo;
}
// handle asynchrony
@action initTodo = async function () {
const res = await new Promise(resolve= > {
setTimeout(() = > {
resolve([]);
}, 1000);
});
// Use the runInAction, or simply invoke an existing action
runInAction(() = > {
this.todo = res;
});
// or
this.setTodo(res);
};
@action setTodo(todo) {
this.todo = todo;
}
// autorun, reaction, when
const disposeRun = autorun(() = > {
console.log('autorun', store.count);
});
// Effect is called only after the return value of the first method is modified
reaction(
// Store. Count will not be called until it is modified
() = > store.count,
(count, reaction) = > {
console.log('reaction', count);
// The reaction is called only oncereaction.dispose(); });// If the first method returns true, effect is immediately called, and the Autorunner is cleaned up
when(
() = > store.count > 10.() = > {
console.log('when', store.count); });// Async,await
async function() {
await when(() = > that.isVisible);
/ / and so on..}}export default Store;
Copy the code
The React component uses:
// The top-level component app.js
import { Provider } from 'mobx-react';
import store from './store';
function App() {
return (
<div className="App">
<Provider store={store}>
<Demo></Demo>
</Provider>
</div>
);
}
/ / child component
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
@inject('store')
@observer
class Demo extends Component {
handleClick = type= > {
let { store } = this.props;
switch (type) {
case 'increment':
store.increment();
break;
case 'decrement':
store.decrement();
break;
case 'reset':
store.resetTableData();
break;
default:}};render() {
let { store } = this.props;
return (
<div>
{store.todo.map(item => {
<span>{item.name}</span>;
})}
<Button onClick={this.handleClick('increment')} ></Button>
</div>); }}// Function components
import React from 'react';
import { inject, observer } from 'mobx-react';
const Demo = inject('store')(
observer(props= > {
const { store } = props;
return <span>{store.count}</span>; }));export default Demo;
Copy the code
mobx 6
See article: Getting Started with Mobx