關於 mobX 在 react 16.8.0 以上的用法
如下例子均取自官網文檔
import { observer, useLocalStore } from 'mobx-react'; const Hooks = observer(() => { const todo = useLocalStore(() => ({ title: 'Click to toggle', done: false, toggle() { todo.done = !todo.done }, get emoji() { return todo.done ? '😜' : '🏃' }, })); return <div onClick={todo.toggle}> <h3>{todo.title} {todo.emoji}</h3> </div> })
能夠看到原來的修飾符@observer
,
如今是使用 HOC 來進行擴展的; react
還有另外的 2 種修飾方法: 優化
1:this
import { useLocalStore, useObserver } from 'mobx-react'; function Person() { const person = useLocalStore(() => ({ name: 'John' })) return useObserver(() => ( <div> {person.name} <button onClick={() => (person.name = 'Mike')}>No! I am Mike</button> </div> ))}
使用 useObserver(()=>JSX.Element)
方法取代 observer(()=>JSX.Element)
spa
2:code
import { Observer, useLocalStore } from 'mobx-react'; function ObservePerson() { const person = useLocalStore(() => ({ name: 'John' })) return ( <div> {person.name} <i>I will never change my name</i> <div> <Observer>{() => <div>{person.name}</div>}</Observer> <button onClick={() => (person.name = 'Mike')}> I want to be Mike </button> </div> </div> )}
使用部分渲染, 只有被 <Observer></Observer>
包裹的才能監聽到對應值的改變server
import React, { FC } from 'react';import { observer, useLocalStore } from 'mobx-react'; function initialFn(source) { return ({ count: 2, get multiplied() { return source.multiplier * this.count }, inc() { this.count += 1 }, }); } const Counter: FC<{ multiplier: number }> = observer(props => { const store = useLocalStore( initialFn, Object.assign({ a: 1 }, props),// 能夠傳任意值 ); return ( <div> <button id="inc" onClick={store.inc}> {`Count: ${store.count}`} </button> <span>{store.multiplied}</span> </div> )})
這種分離的方法,基本已經耦合性已經很低了ip