关于mobx:mobx该怎么组织和划分store

8次阅读

共计 869 个字符,预计需要花费 3 分钟才能阅读完成。

在平时我的项目开发中,发现前端同学在进行数据管理时存在有如下问题:

  • 进行到开发前期发现有些 store 体积异样宏大,动辄上千行代码,影响代码的可读性、维护性;
  • 很多 store 之间存在通信的场景,而之前组织的形式不便于 store 之前的通信;
  • 多人合作开发时难免会同时更改同一个store,不可避免的造成代码抵触;

鉴于上述问题,在本次事变单导购我的项目中将对 store 的组织与划分做出如下改良:

  • 思考到每次前端工作都是依据 UI 模块来拆解、调配的,为了更加符合每个前端开发人员的工作,防止工作穿插。当初,store依据 UI 模块来划分,每一个 UI 模块划分出两个 store,一个UI store,一个Domain storeUI store 是指以后 UI 的状态,比方:窗口尺寸、以后展现的页面、渲染状态、网络状态等等;Domain store次要蕴含页面所需的各种数据,带有业务性的数据(个别是须要从后端获取的)。

  • 创立一个 RootStore 来实例化所有 stores,并共享援用,使得所有的 childStore 都能通过 rootStore 进行通信,不必再像之前应用回调的模式实现通信。


示例:

class RootStore {constructor() {this.userStore = new UserStore(this)
 this.todoStore = new TodoStore(this)
 }
}
​
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}
}

参考:https://cn.mobx.js.org/best/s…

正文完
 0