小编典典

使用mobx创建多个商店并将其注入到组件的正确方法-ReactJs

reactjs

如Mobx 文档中的建议,我以以下方式创建了多个商店:

class bankAccountStore {
  constructor(rootStore){
    this.rootStore = rootStore;
  }
...

class authStore {
  constructor(rootStore){
    this.rootStore = rootStore;
  }
...

最后以以下方式 创建根存储
。另外,我更喜欢在master商店构造函数中构造子商店。此外,我发现有时我的子存储必须观察父存储的一些数据,因此我将其传递给子构造函数

class RootStore {
  constructor() {
    this.bankAccountStore = new bankAccountStore(this);
    this.authStore = new authStore(this);
  }
}

通过 以下方式 提供给应用程序

<Provider rootStore={new RootStore()}>
  <App />
</Provider>

然后像这样 注入组件

@inject('rootStore') 
@observer
class User extends React.Component{
  constructor(props) {
    super(props);
    //Accessing the individual store with the help of root store
    this.authStore = this.props.rootStore.authStore;
  }
}

即使它需要一部分根存储库,还是每次都将根存储库注入组件的正确有效的方法吗? 如果不是,如何将auth Store注入用户组件?

编辑:我已经做出了结束github讨论的答案。 答案中提供的讨论链接


阅读 940

收藏
2020-07-22

共1个答案

小编典典

这个答案可能是有道理的,但可以间接地帮助社区。
经过大量研究,我看到许多人在实践中使用以下方法。常规方法具有一个根存储,该根存储可以充当存储之间的通信通道。

问题1:如何组织商店并将其注入到组件中?

方法1:

App.js

// Root Store Declaration
class RootStore {
    constructor() {
      this.userStore = new UserStore(this);
      this.authStore = new AuthStore(this);
    }
}    
const rootStore = new RootStore()

// Provide the store to the children
<Provider 
    rootStore={rootStore}
    userStore={rootStore.userStore}
    authStore={rootStore.authStore}
>
  <App />
</Provider>

Component.js

// Injecting into the component and using it as shown below
@inject('authStore', 'userStore')
@observer
class User extends React.Component {
    // only this.props.userStore.userVariable
}

方法二:

App.js

class RootStore {
    constructor() {
      this.userStore = new UserStore(this);
      this.authStore = new AuthStore(this);
    }
} 
const rootStore = new RootStore()

<Provider rootStore={rootStore}>
  <App />
</Provider>

Component.js

// Injecting into the component and using it as shown below
@inject(stores => ({
    userStore: stores.userStore,
    authStore: stores.authStore,
    })
)
@observer
class User extends React.Component {
    // no this.props.rootStore.userStore,userVariable here, 
    // only this.props.userStore.userVariable
}

方法1和方法2除了语法差异外没有其他差异。好的!那是注射部分!

问题2:如何进行店间交流? (尽量避免)

现在,我知道一个好的设计可以使商店保持独立,并减少耦合。 但是以某种方式考虑一种情况,UserStore如果某个变量in AuthStore
发生变化,我希望变量in 发生变化。使用Computed。这两种方法都通用

AuthStore.js

export class AuthStore {    
    constructor(rootStore) {
        this.rootStore = rootStore
        @computed get dependentVariable() {
          return this.rootStore.userStore.changeableUserVariable;                                      
        }
    }
}

我希望这对社区有所帮助。有关更详细的讨论,您可以参考我在Github上提出问题

2020-07-22