官方提供的文档在这里:https://github.com/mobxjs/mob... 不喜欢看英文的看我这里吧~
import { action, observable } from 'mobx'; class Store { @observable count = 1; @action setCount = () => { this.count++; } } export const store = new Store();
// 注入store import { Provider } from 'mobx-react'; import {store} from './store'; <Provider store={store}> <Demo /> </Provider>
import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; @inject('scope') @observer class Demo1 extends Component { render() { return <div>{this.props.count}</div> } }
import React from 'react'; import { useObserver, Observer, useLocalStore } from 'mobx-react'; import {store } from './store'; // 方法1 function Demo2() { const localStore = useLocalStore(() => store); return useObserver(() => <div onClick={localStore.setCount}>{localStore.count}</div>) } // 方法2,更新Observer包裹的位置,注意这里包裹的必须是一个函数 function Demo3() { const localStore = useLocalStore(() => store); return <Observer>{() => <span>{localStore.count}</span>}</Observer> }
好了,放心的把 Mobx+Hooks 加入到自己的项目中去吧~