mobx在react hooks中的應用

hooks 實現inject功能

// utils/useStores.js
import React from 'react'
import { MobXProviderContext} from 'mobx-react';
import RootStore from '~/stores/index'
const useStores = (name) => React.useContext(MobXProviderContext)[name]

export default useStores

局部的store

// store.js

import { observable, action } from 'mobx';
class Store {
  @observable userInfo = { name: 'xsx' };
  @observable count = 11;
  @action
  handleClick() {
    this.count +=1;
  }
}
export default Store;

頁面中使用

import React, { ReactElement } from 'react';
import Store from './store.ts';
import useStores from '~/utils/useStores';
import { useObserver, useObservable } from 'mobx-react-lite';

interface Props {
  [props: string]: any;
}

export default function index(props: any): ReactElement {
//  手動傳入字符串,選擇要使用的內容 該處爲全局store的引用,與之前的class下的@inject('userStore')同理
  const globalStore = useStores('userStore'); 
  // 添加觀察者模式 該處爲局部的store 與之前class下的  let myStore = new Store(); 同理
  let myStore = useObservable(new Store()); 

  return useObserver(() => (
    <div>
      {myStore.count}
      ====================
      {store.count}
      <button
        onClick={() => {
          myStore.handleClick();
          globalStore .handleClick();
        }}
      >
        add
      </button>
    </div>
  ));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章