zoukankan      html  css  js  c++  java
  • 在hooks中使用Mobx[转载]

    转载:https://segmentfault.com/a/1190000022335345

     

    如果你的项目用了Mobx,部分又用到了Hooks

    1、创建store

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

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

    // 注入store
    import { Provider } from 'mobx-react';
    import {store} from './store';
    
    <Provider store={store}>
      <Demo />
    </Provider>

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

    4、在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>
    }
  • 相关阅读:
    英文词频统计预备,组合数据类型练习
    凯撒密码、GDP格式化输出、99乘法表
    字符串基本操作
    条件、循环、函数定义 练习
    Turtle库基础练习
    Python基础练习
    理解管理信息系统
    HTML鼠标划过更换图片(透视X-ray)
    谷歌浏览器默认允许flash运行
    鼠标单击烟花效果
  • 原文地址:https://www.cnblogs.com/xiaozhumaopao/p/13737897.html
Copyright © 2011-2022 走看看