zoukankan      html  css  js  c++  java
  • mobx在hooks中使用

    创建仓库还是和之前一样,在 store/index.js 中

    import { observable } from "mobx";
    
    class store {
        @observable a = "1154545";
        @observable count = 1;
    
        @action
        setCount = () => {
            this.count++;
        }    
    }
    export default store;
    1. 注入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('store')
    @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>
    }
  • 相关阅读:
    ios开发-2015-07-19
    ios开发-2015-07-18
    ios开发-2015-07-17
    ios开发-2015-07-16
    ios开发-2015-07-15
    ios开发-2015-07-14
    ios开发-2015-07-13
    Selenium源码分析之WebDriver
    webdriver实现原理 分类: Selenium 2015-07-16 00:16 11人阅读 评论(0) 收藏
    webdriver实现原理
  • 原文地址:https://www.cnblogs.com/tommymarc/p/15768138.html
Copyright © 2011-2022 走看看