素材牛VIP会员
mobx多个store问题
 面***笑  分类:JavaScript  人气:1234  回帖:2  发布于6年前 收藏

我在react中使用mobx做状态管理实现了简单计数器demo,如果该页面今后需要添加新的功能,我希望不同功能存放在不同的store,请问这要如何实现

countStore.js

import { observable,action, computed } from 'mobx';
class CountStore{
    @observable num = 0;
    @computed get displayResult(){
        return this.num;
    }
}

export default CountStore;

app.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Count from './count';
import Display from './display';
import CountStore from "../store/countStore";
const CountStores = new CountStore();
class Countapp extends Component{
    constructor(props){
        super(props)
    }

    render(){
        return <div>
            
            <Count store={CountStores}/>
            <Display store={CountStores}/>
            
        </div>
    }
}

export default Countapp;

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv2 入门
龙***c 技术总监 6年前#1

Mobx类似于Redux,也是有Provider方法,可以把Store挂载到整个应用上,至于多个Store实现起来也是简单的,给个例子:

storeA.js

import {observable, action} from 'mobx';

class AStore {
  //……
}

const aStore = new AStore()

export {aStore}

storeB.js

import {observable, action} from 'mobx';

class BStore {
  //……
}

const bStore = new BStore()

export {bStore}

index.js

import {bStore} from './storeA'
import {bStore} from './storeB'

export {bStore, bStore}

具体可以看看我的项目>>react-mobx-demo

顺便再给个Redux的项目>>react-redux-demo

Lv4 码徒
蝶***7 UI设计师 6年前#2

再写一个store.js文件就可以了

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取