使用mobx 创建前端store并使用


话不多说直接上代码
1.使用mobx需要下载mobx和mobx-react两个依赖包

 

2.写一个store的类文件比如:

      import { observable, action } from 'mobx'
      class Mobx1 {
              @observable number;

               constructor() {
                     this.number = 0
                 }

              @action
               addNumber = (number) => {
                    this.number = number
               }

       }
      const MyMobx = new Mobx1();
      export { MyMobx };

3. 新建总的store文件,将store的类文件注入到总的store文件中
 
    import { MyMobx } from './mobx'
    const store = {
            MyMobx
     }

    export default store
 

4. 将总的store文件注入到路由的外层,也是页面的外层

 

 

 

 

 5. 在使用页面中需要先用inject注入使用的store类,在使用this.props下的这个store类的方法及属性

 

 

然后就能愉快的使用了哈哈 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM