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>
));
}
版权声明:本文为qq_36676237原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。