您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

// 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>

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

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

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

// 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除了语法差异外没有其他差异。好的!那是注射部分!

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

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

其他 2022/1/1 18:18:16 有360人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶