在hooks中使用Mobx


創建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> } } 

豌豆資源搜索網站https://55wd.com 廣州vi設計公司http://www.maiqicn.com

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM