在hooks中使用Mobx

若是你的項目用了Mobx,部分又用到了Hooks

官方提供的文檔在這裏:https://github.com/mobxjs/mob... 不喜歡看英文的看我這裏吧~javascript

  1. 建立store
import { action, observable } from 'mobx';

class Store {
    @observable
    count = 1;
    
    @action
    setCount = () => {
        this.count++;
    }
}
export const store = new Store();
  1. 注入store,這樣既能夠在class中使用,也能夠在hooks中使用了
// 注入store
import { Provider } from 'mobx-react';
import {store} from './store';

<Provider store={store}>
  <Demo />
</Provider>
  1. 在class中使用
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>
    }
}
  1. 在hooks中使用
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 加入到本身的項目中去吧~java

相關文章
相關標籤/搜索