问题遇到的现象和发生背景
在学习react配合mobx的过程中,需要将mobx的store进行模块化
项目结构:
src
├─App.jsx
├─index.js
├─store
| ├─count.Store.js
| ├─index.js
| └list.Store.js
├─components
| ├─Count.jsx
| └List.jsx
count.Store.js和list.Store.js分别是子模块的store文件。
/src/store/index.js是根模块的入口文件,在这里封装导出子模块的方法。
问题相关代码,请勿粘贴截图
import React, { useContext } from "react";
import { CountStore } from "./count.Store";
import { ListStore } from "./list.Store";
class RootStore {
constructor() {
this.countStore = new CountStore()
this.listStore = new ListStore()
}
}
const rootStore = new RootStore()
const context = React.createContext(rootStore)
const useStore = () => useContext(context)
export { useStore }
为什么这里要把实例化对象注入context呢?
为什么不可以直接使用rootStore这个实例化对象,而要重新封装一个useStore的方法?
我的解答思路和尝试过的方法
我尝试了直接使用rootStore这个实例化对象(export {rootStore}
),也是可以的,效果和使用useStore是一模一样的,那这里用React下的context去封装useStore方法有什么实际意义?感觉就像换了个名字而已。但是既然这个代码原本是使用useStore的那就有它的道理,可能是我水平不够不知道封装useStore的好处……求解答!!