Mobx入门和较佳实践

以前讲到过咱们团队从redux迁移到mobx,为何咱们抛弃了redux呢?一个很重要的缘由就是使用redux开发,代码量增多,复杂度增大,同时须要维护api,action,reducer,即便是借助redux-thunk或者redux-promise这样的中间件,action这一层的代码量感受仍是太多了,光是actionType的命名都须要斟酌思考,mobx将action和reducer结合到了一块儿,省去了type的命名,以及es6+的装饰器的引入,整个代码量和复杂度下降了很多,自从用了mobx整我的都轻松了许多!vue

首先简单介绍一下mobx,他和redux相似数据都是单向流动,经过action改变state,促使view更新 react

img

下面让咱们来撸一个简单的例子吧es6

//store.js
import { observable, autorun, flow, computed, when, reaction, action } from 'mobx';
import * as api from './api';

class UserStore {
    @observable
    basicInfo = {};
    
    // constructor函数里面能够放一些初始化的action
    constructor() {
        // when若是没有第二个参数,则返回一个promise,配合await或yield使用
        when(   
            // 一旦...
            () => false,
            // ... 而后
            () => this.dispose()
        )
    }
    
    // 在observable对象发生变化时,会调用,第二个参数表示配置,有delay和onError
    auto = autorun(
        e => {
            // console.log(e);
        },
        { delay: 3000 }
    );
    
    // autorun的变种,能够更精确的配置对象的属性
    myReaction = reaction(() => this.isLogined, isLogined => console.log('myReaction'));
    
    // 相似vue中computed的用法
    @computed
    get total() {
        console.log(this.currentStaffInfo);
        return this.currentStaffInfo;
    }

    getBasicInfo = flow(function*() {
        try {
            // 这里也能够调用其余action
            this.basicInfo = (yield api.queryInfo()).payload;
        } catch (error) {
            this.basicInfo = {};
        }
    });
    
    @action
    setBasicInfo = value => {
        this.basicInfo = value;
    };
}

export default new UserStore();
复制代码
//User.jsx
import React, { Component } from 'react';
import { observer, Provider, inject } from 'mobx-react';
import UserStore from './store';

@inject('UserStore')
@observer
class User extends Component {
    componentDidMount() {
        this.props.UserStore.getBasicInfo()
    }
    render() {
        return (
            <div>
                {this.props.UserStore.basicInfo.name}
            </div>
        );
    }
}

export default (
    <Provider UserStore={UserStore}>
        <User />
    </Provider>
);
复制代码

这样就大功告成啦,怎么样,mobx是否是特别简单清爽,mobx还有不少其余特性,但愿你们可以多多去探索交流!redux

相关文章
相关标签/搜索