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

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

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

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

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

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;
  }
}

问题1:这是不是每次都将根存储注入组件的正确和最有效的方法,即使它需要根存储的一部分?

问题 2:如果没有,将 auth 存储注入用户组件的最佳方法是什么?

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

解答

这个答案可能是固执己见,但它可能间接地帮助社区。

经过大量研究,我看到了许多人在实践中使用的以下方法。通用方法 有一个根存储,可以充当存储之间的通信通道。

问题 1:组织 store 并将其注入组件的最佳方式是什么?

方法一:

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>

组件.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
}

方法2:

App.js

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

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

组件.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:商店之间最好的沟通方式是什么? (尽量避免)

现在我知道一个好的设计可以让商店保持独立并且减少耦合。但是以某种方式考虑一个场景,如果AuthStore中的某个变量发生变化,我希望UserStore中的变量发生变化。使用Computed。这种方法对上述两种方法都很常见

AuthStore.js

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

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

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐