首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mobx:更改来自另一个商店的商店的值

Mobx:更改来自另一个商店的商店的值
EN

Stack Overflow用户
提问于 2019-07-11 17:06:36
回答 1查看 1.1K关注 0票数 0

我正在使用带有钩子的mobx-react-lite。

我有两家店。AuthStore SomeOtherStore

这是我的虚拟AuthStore

代码语言:javascript
复制
import { observable, decorate, action } from 'mobx';
import { createContext } from 'react';
import { ROLE_LOGISTICS_MANAGER } from '../settings/constants';
import AuthService from '../services/AuthService';

class AuthStore {
  constructor() {
    this.authService = new AuthService();
  }

  currentMode = ROLE_LOGISTICS_MANAGER;

  authenticating = true;

  isLoggedIn = false;

  userId = null;

  loginLoading = false;

  login = async params => {
    this.loginLoading = true;
    try {
      const data = await this.authService.loginAsync(params);
      this.loginLoading = false;
      this.isLoggedIn = true;
    } catch (e) {
      console.error(e);
      this.loginError = e;
    } finally {
      this.loginLoading = false;
    }
  };
}
decorate(AuthStore, {
  currentMode: observable,
  loginLoading: observable,
  isLoggedIn: observable,
  authenticating: observable,
  userId: observable,
  fetchUser: action,
  login: action
});
export const AuthStoreContext = createContext(new AuthStore());

现在假设我想从另一个商店更改isLoggedIn,我该怎么做呢?我试图在文档中找到方法,但找不到可靠的解决方案。我将钩子与mobx-react-lite一起使用,所以通常我会使用mobx,比如

代码语言:javascript
复制
const authStore = useContext(AuthStoreContext);
EN

回答 1

Stack Overflow用户

发布于 2019-07-13 14:33:32

这是一种常见的模式,将存储作为属性存储在RootStore上,每个属性都有对根的引用。所以你可以有一个类似这样的结构:

代码语言:javascript
复制
class RootStore {
  constructor (auth, ui) {
    this.auth = new AuthStore(this)
    this.ui = new UiStore(this)
  }
}

class AuthStore {
  constructor (rootStore) {
    this.rootStore = rootStore
  }

  logout() {
    this.isLoggedIn = false
  }
}

decorate(AuthStore, {
  logout: action
})

然后,当您需要调用另一个存储上的函数时,您可以使用对根的引用作为路径。该模式在here中有更详细的描述。使用useContext的一个可能示例可能是:

代码语言:javascript
复制
const { someStore } = useContext(rootStoreContext)
someStore.rootStore.auth.logout()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56985535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档