在hooks中使用Mobx

摘要:创建store;注入store,这样既可以在class中使用,也可以在hooks中使用了;在class中使用;在hooks中使用

创建store

import { action, observable } from 'mobx';

class Store {
    @observable
    count = 1;
    
    @action
    setCount = () => {
        this.count++;
    }
}
export const store = new Store();

注入store,这样既可以在class中使用,也可以在hooks中使用了

// 注入store
import { Provider } from 'mobx-react';
import {store} from './store';

<Provider store={store}>
  <Demo />
</Provider>

在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>
    }
}

在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 加入到自己的项目中去吧~

原文:https://segmentfault.com/a/1190000022335345

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_8568