我正在使用带有钩子的mobx-react-lite。
我有两家店。AuthStore SomeOtherStore
这是我的虚拟AuthStore
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,比如
const authStore = useContext(AuthStoreContext);发布于 2019-07-13 14:33:32
这是一种常见的模式,将存储作为属性存储在RootStore上,每个属性都有对根的引用。所以你可以有一个类似这样的结构:
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的一个可能示例可能是:
const { someStore } = useContext(rootStoreContext)
someStore.rootStore.auth.logout()https://stackoverflow.com/questions/56985535
复制相似问题