亞寵展、全球?qū)櫸锂a(chǎn)業(yè)風(fēng)向標(biāo)——亞洲寵物展覽會(huì)深度解析
628
2022-05-29
Mobx的介紹
Mobx使用流程
創(chuàng)建項(xiàng)目
npx create-react-app mobx
進(jìn)入項(xiàng)目
cd mobx
項(xiàng)目抽離
yarn eject
安裝mobx mobx-react
yarn add mobx mobx-react
注意: 如果git沖突 解決: 我們要原操作先放到本地暫存盤 git add . git commit -m '安裝mobx mobx-react' 注意不要git push
配置裝飾器(修飾器 es6 ) babel
yarn add babel-plugin-transform-decorators-legacy -D yarn add @babel/preset-env -D yarn add babel-plugin-transform-class-properties -D yarn add @babel/plugin-proposal-decorators -D
1
2
3
配置package.json
"babel": { "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ], "transform-class-properties" ], "presets": [ "react-app", "@babel/preset-env" ] },
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
注意: 以下兩個(gè)配置順序不可更改
[ "@babel/plugin-proposal-decorators", { "legacy": true } ], "transform-class-properties"
1
2
3
4
5
6
項(xiàng)目中 mobx應(yīng)該怎么用?
新建store目錄
src下建立
src store home index.js car index.js index.js
以這種結(jié)構(gòu)建立文件和目錄
在主入口文件中 使用 Provider
import store from './store' import { Provider } from 'mobx-react' ReactDOM.render(
1
2
3
4
5
6
7
8
打造mobx 數(shù)據(jù)包
import { observable, computed,action } from 'mobx' class Home { @observable //監(jiān)聽 age age = 18 @computed //當(dāng)age發(fā)生改變時(shí), 自動(dòng)觸發(fā) get doubleAge(){ return this.age *= 2 } @action // 用戶操作 事件調(diào)用 increment(){ this.props.store.home.age ++ console.log( this.props.store.home.age ) //數(shù)據(jù)請求 fetch('/data/data.json') .then(res => res.json()) .then( result => console.log( result )) .catch( error => console.log( error )) } } const home = new Home() export default home
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
打造store
store/index.js
import home from './home' const store = { //實(shí)例 home } export default store
1
2
3
4
5
6
組件內(nèi)使用數(shù)據(jù)
this.props.store.xxx 可以拿到數(shù)據(jù)
注意:
this.porps里面沒有找到 @action 裝飾器定義的方法, 但是可以直接使用,
this會(huì)丟失 this.props.store.home.increment.bind(this)
在你要使用store的組件上記得做觀察
import React,{ Component,Fragment } from 'react' import { inject,observer } from 'mobx-react' @inject('store') @observer class Count extends Component { constructor ( props ) { super( props ) props.store.count.change = props.store.count.change.bind( this )//this丟失的解決 } increment = () => { console.log( 'mine' ) this.props.store.count.change() } render () { return ( count:{ this.props.store.count.count}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
MobX React
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。