Mobx 4.x-5.x
Mobx core Concepts:
- mobx.observable
Changes an object’s properties to observable properties
/ / the original writing
observable({
count: 0
});
// The decorator
class Store {
@observable count = 0
}
Copy the code
- mobx.action
Used to define functions that change the state
/ / the original writing
action(() = > {
store.count++
})
// The decorator
@action setCount = () = > {
this.count++
}
Copy the code
3. Calculate attributes
/ / the original writing
const orderLine = observable.object({
price: 0.amount: 1.get total() {
return this.price * this.amount
},
set total(total) {
this.price = total / this.amount // Derive price from total}})// The decorator
class Foo {
@observable length = 2;
@computed get squared() {
return this.length * this.length;
}
set squared(value) { // This is an automatic action that requires no annotations
this.length = Math.sqrt(value);
}
Copy the code
Mobx-React
- observer
Convert the React component to a responsive component
/ / the original writing
function Home () {
return(...). }export default observer(Home)
// The decorator
@observer
class Home extends React.Component{
render () {
return(...). }}Copy the code
Version compatibility
Mobx5
Need to cooperatereact16.x
Using MOBx5 with Act17 will cause an error.
Babelrc syntax compatible
"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true}].Copy the code