如何组织Mobx中的Store之一:构建State、拆分Action

在之前第一篇1中,主要描述在使用Redux中碰到的两个问题以及由Mobx最佳实践中自己的对于组织Store的自己的看法,之后也有尝试过几种不同的Mobx的Store的组织方案,在这里和大家分享一下自己的经验

前言

关于不按照页面来区分store是这系列文章的前提。第一篇想首先就Store的构建和Action的拆分给出一些建议,后期还会介绍Mobx的后端渲染和持久化、序列化的一些方案。

关于常见的store和action的组织方案

在第一篇里,一个简单的瀑布流+详情的页面中,我将获取详情的action直接放到了详情的对象里(store)。

class Detail {
	id: string
	// ...其他属性 
	constructor(item: any) {
		extendObservable(this, item)
	}
	@action('获取详情') async fetch() {
		const data = await requestFromServer(this.id)
		extendObservable(this, data)
	}
	@action('保存编辑') async save(data) {
		extendObservable(this, data)
		await submitToServer(data)
		await this.fetch()
	} 
}

并且在大多数的事例的Mobx的项目中,都是这样组织action和store的,例如:

这种组织方式的好处是,在action和store一一对应的系统中,我们可以很容易找到操作该store的所有action,代码结构比较直观。

遇到的问题

首先说会遇到的问题:store实例与实例之间过于耦合了,在上面首页feed流(HomeStore)的store对象中的action里,我们会需要操作一个详情map的store的实例。同理,推荐列表的store也一样。

如此,整个store和action就会被耦合成一个整体,当我们需要时,我们只能够一次性生成整个store。当我们要改动任意一个,可能就会触发这个整体的问题,不够灵活。

所以,store和action应当是分离的,只要对外提供的接口相同,内部实现可以随意变化。并且不同store之间的数据应当也是互相分离的,不会有实例间的互相引用,不同的action类别也可以拆分出来,对单个或者多个state(store的实例)进行操作。

重新组织action和store

首先明确store和action的概念,store是指在应用中唯一存储数据的地方,而action则是所有触发store数据变化的地方(在Mobx中没有reducer和dispatch的概念,action直接触发store改动并且同步的响应在页面中)。

根据这个概念,将action拆分出来。

还是以上一篇文章的例子来说:

一个首页(文章的feed流)、各个文章详情页、推荐列表页。

Stores

Store中只存数据

export class HomeStore {
	@observable feed: string[] = []
}

class MapStore<T> {
	@observable data = asMap<T>({})
	// 获取,可以在该方法中做各种容错
	get(id: string) { return this.data.get(id) }
	// 设置
	set(id: string, value: T) { this.data.set(id, value) }
	// 判断
	has(id: string) { return this.data.has(id) }
	// 合并数据,可以在该方法中做各种容错
	merge(id: string, value: T) { /*...*/ }
}

export class Detail {
	id: string = null
	@observable title: string = null
	// ...other properties
}

export class DetailStore extends MapStore<Detail> {}

export class Recommend {
	id: string = null
	@observable list: any[] = []
}

export class RecommendStore extends MapStore<Recommend> {}

Actions

只在Action中操作数据

export HomeActions {
	private home: HomeStore
	private details: DetailStore
	constructor({ home, details } as any) {
		this.home = home
		this.details = details
	}
	@action async fetch(pn: number = 1) {
		this.home.feed = await fetch(url).then(res => res.json()).map(item => {
			this.details.merge(item.id, item)
			return item.id
		})
	}
}

export DetailActions {
	private details: DetailStore
	constructor({ details } as any) {
		this.details = details
	}
	@action async fetch(id: string) {
		this.details.merge(id, await fetch(url))
	}
	@action async save(data: any) {
		/* ... */
	}
}

export RecommendActions {
	private recommend: RecommendStore
	private details: DetailStore
	constructor({ home, details } as any) {
		this.home = home
		this.details = details
	}
	@action async fetch(pn: number = 1) {
		this.recommend.list = await fetch(url).then(res => res.json()).map(item => {
			this.details.merge(item.id, item)
			return item.id
		})
	}
}

Components

组建或者页面中的store都是由注入的方式提供的。

import * as React from 'react'
import { observer } from 'mobx-react/native'


observer(['home', 'details'])
export class Home
	extends React.Component<{ home: HomeStore, details: DetailStore}, {}> {
}

效果

实际上在我们的stores和actions中,我们只是声明了他们,而并没有生成实例,当我们的app启动时,我们首先需要新建store和action。

import {
	HomeStore,
	DetailStore,
	RecommendStore
} from './stores'
import {
	HomeActions,
	DetailActions,
	RecommendActions
} from './store'

const mobxStates = {
	home: new HomeStore,
	details: new DetailStore,
	recommends: new RecommendStore,
}
const actions = {
	home: new HomeActions(mobxStates),
	detail: new DetailActions(mobxStates),
	recommend: new RecommendActions(mobxStates)
}

export function App(props: any) {
	return <Provider
		{...mobxStates}
		actions={actions}
	>{routes}</Provider>
}

还是以一个首页为例子吧

import * as React from 'react'
import { View, Text, ListView } from 'react-native'
import { observer } from 'mobx-react/native'

const ds = new ListView.DataSource({
	rowHasChanged: (r1, r2) => r1 !== r2
})

interface HomeProps {
	home: HomeStore
	details: DetailStore
}

@observer['home', 'details']
export class Home extends React.Component<HomeProps, {}> {
	render () {
		const { home, details } = this.props
		const list = home.feed.map(id => details.get(id))
	
		return <ListView
			dataSource={ds.cloneWithRows(list)}
	        renderRow={(item) => <Text>{item.content}</Text>}
		/>
	}
}

Back