亲宝软件园·资讯

展开

React Mobx状态管理工具的使用

碰磕 人气:0

Mobx与redux的区别

使用

安装

npm i mobx@5

使用严格模式

configure({
    enforceActions:'always'
})

observable&&autorun

import React,{Component} from 'react';
import {observable,autorun} from 'mobx';
/**
 * 基本类型
 */
//对于普通类型数据的监听
let observableNumber=observable.box(66)
let observableDesc=observable.box("学无止境...")
//第一次执行一次,之后被改变与它相关的会再次执行
autorun(()=>{
  console.log(observableNumber.get())
})
setTimeout(() => {
  observableNumber.set(11)
  observableDesc.set("爱学.")
}, 2000);
/**
 * 对象使用map
 */
let myobj=observable.map({
  name:"碰磕",
  age:9999
})
autorun(()=>{
  console.log("对象name属性改变了"+myobj.get("name"))
})
class Zhuye extends Component{
  render() {
    return (  
      <div>
        Mobx
      </div>
    );
  };
};
export default Zhuye;

action

专门修改可观察的value

import {observable,autorun,action} from 'mobx'
const store=observable({
    isTabbarShow:true,
    list:[],
    cityName:"北京",
    changeShow(){
        this.isTabbarShow=true
    },
    changeHide(){
        this.isTabbarShow=false
    }
},{
    changeHide:action,
    changeShow:action//标记两个方法是action,专门修改可观察的value
})
export default store

然后在需要改变isTabbarShow的地方调用方法即可…

使用装饰器写法

import {observable,autorun,action} from 'mobx'
class Store{
    @observable isTabbarShow=true
    @observable list=[]
    @action changeShow(){
        this.isTabbarShow=true
    }
    @action changeHide(){
        this.isTabbarShow=false
    }
}
const store=new Store()
export default store

由于不支持装饰器写法,需要让它支持

1.安装依赖:

npm i @babel/core @babel/plugin-proposal-decorators @babel/preset-env

2.创建.babelrc{

    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        [
            "@babel/plugin-proposal-decorators",
            {
                "legacy": true
            }
        ]
    ]
}

3.创建config-overrides.js

const path = require('path')
const { override, addDecoratorsLegacy } = require('customize-cra')
function resolve(dir) {
    return path.join(__dirname, dir)
}
const customize = () => (config, env) => {
    config.resolve.alias['@'] = resolve('src')
    if (env === 'production') {
        config.externals = {
            'react': 'React',
            'react-dom': 'ReactDOM'
        }
    }
    return config
};
module.exports = override(addDecoratorsLegacy(), customize())

4.安装依赖

npm i customize-cra react-app-rewired

5.修改package.json

----...
"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test":  "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
----....

vscode需要配置

文件—首选项----设置-----搜索experimentalDecorators----勾上该设置

最后重新运行即可…

runInAction(异步)

异步请求时需要,在严格模式下

import axios from 'axios'
import {observable,autorun,action,runInAction, configure} from 'mobx'
configure({
    enforceActions:'always'
})
class Store{
    @observable isTabbarShow=true
    @observable list=[]
    @action changeShow(){
        this.isTabbarShow=true
    }
    @action changeHide(){
        this.isTabbarShow=false
    }
    @action getList(){
        axios({
            method:'GET',
            url:"https://m.maizuo.com/gateway?cityId=440300&ticketFlag=1&k=2005318",
            headers:{
                "X-Client-Info": '{"a":"3000","ch":"1002","v":"5.2.0","e":"1654433035923688551579649"}',
                "X-Host": "mall.film-ticket.cinema.list"
            }    
        }).then(res=>{
            runInAction(()=>{
                this.list=res.data.data.cinemas
            })
        })
    }
}
const store=new Store()
export default store

这样就可以修改this.list的了

Mobx的基本使用就大功告成了

加载全部内容

相关教程
猜你喜欢
用户评论