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(() => (
    
{myStore.count} ==================== {store.count}
)); }

你可能感兴趣的:(mobx)