使用mobx进行状态管理相比于redux显得更加的轻量级,mobx采用响应式编程,主要采用观察者模式,redux使用不开心不妨试试mobx
下面主要说明在项目中使用mobx如何友好组织多个store,以及在view层注入我们想使用的store
store.js
import {observable} from 'mobx';
class UserStore {
constructor(rootStore) {
this.rootStore = rootStore
}
getTodos(user) {
// 通过根 store 来访问 todoStore
return this.rootStore.todoStore.todos.filter(todo => todo.author === user)
}
}
class TodoStore {
@observable todos = []
constructor(rootStore) {
this.rootStore = rootStore
}
}
class RootStore {
constructor() {
this.userStore = new UserStore(this)
this.todoStore = new TodoStore(this)
}
}
export default new RootStore()
将根store(rootStore)注入到view层根组件之中(App.js),这一点类似与react-redux
import React from 'react';
import {Provider, observer} from 'mobx-react';
import rootStore from './store/store';
import Demo from './views/Demo';
class App extend React.Component {
render() {
return (
<Provider rootStore={rootStore}>
<Demo />
</Provider>
)
}
}
export default App;
Demo组件
import React from 'react';
import {inject, observer} from 'mobx-react';
@inject('rootStore') //注入Provider提供的rootStore到该组件的props中
@observer //设置当前组件为观察者,一旦检测到store中被监测者发生变化就会进行视图的强制刷新
class Demo extends React.Component {
constructor(props) {
super(props);
console.log(props);
}
render() {
let rootStore = this.props.rootStore;
return (
<div className="demo">
{
rootStore.todoStore.map(function(item, index) {
return (
<div>{item.content}</div>
)
})
}
</div>
)
}
}
export default Demo;
整体的rootStore注入机制采用react提供的context来进行传递