React中的状态管理---Mobx

网友投稿 463 2022-05-29

Mobx的介绍

Mobx使用流程

创建项目

npx create-react-app mobx

进入项目

cd mobx

项目抽离

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

注意: 以下两个配置顺序不可更改

[ "@babel/plugin-proposal-decorators", { "legacy": true } ], "transform-class-properties"

1

2

3

4

5

6

项目中 mobx应该怎么用?

新建store目录

src下建立

src store home index.js car index.js index.js

以这种结构建立文件和目录

在主入口文件中 使用 Provider

import store from './store' import { Provider } from 'mobx-react' ReactDOM.render( , document.getElementById('root'));

1

2

3

4

5

6

7

8

打造mobx 数据包

import { observable, computed,action } from 'mobx' class Home { @observable //监听 age age = 18 @computed //当age发生改变时, 自动触发 get doubleAge(){ return this.age *= 2 } @action // 用户操作 事件调用 increment(){ this.props.store.home.age ++ console.log( this.props.store.home.age ) //数据请求 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 = { //实例 home } export default store

1

2

3

4

5

6

组件内使用数据

this.props.store.xxx 可以拿到数据

注意:

this.porps里面没有找到 @action 装饰器定义的方法, 但是可以直接使用,

this会丢失 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}

) } } export default Count

1

2

3

4

5

6

7

8

9

10

11

12

13

14

React中的状态管理---Mobx

15

16

17

18

19

20

21

22

23

24

MobX React

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:vim编辑器,应该这样用!
下一篇:Linux系列:vim编辑器,应该这样用!
相关文章