MobX和商店之间的连接

问题描述 投票:3回答:1

家伙。我正在开发ract + mobx + firebase app。我想将我的app逻辑分成3个商店:

  • authStore - 存储,其中发生所有firebase auth操作
  • userStore - 存储来自firebase数据库的所有当前用户数据
  • edtorStore - 编辑器组件中发生的所有事情。

因此,要从db接收currentUser数据,我首先需要从fb.auth()获取currentUser.uid。我的AuthStore看起来像这样:

class AuthStore {
    @observable auth = {
        authUser  : null,
        authError : null
    };

    constructor () {
        console.log ( 'start auth' );
        this.unwatchAuth = Fb.auth.onAuthStateChanged ( user => {
            console.log ( 'status changed' );
            this.auth.authUser = user;
        } );
    }

    @computed
    get currentUser () {
        console.log ( 'updated' );
        return this.auth.authUser;
    }
}

const authStore = new AuthStore ();
export { authStore };

我的用户商店:

class CurrentUser {
    @observable user = ( {} );
    constructor () {
            this.userRef       = Fb.dbRoot.ref ( `users/${user.uid}` );
            this.userRef.on ( 'value', ( snapshot ) => {
                this.user = snapshot.val ();
            } );
        } );
    }
}

const user = new CurrentUser ();
export { user };

我导入一家全球商店的所有商店

import { authStore } from './AuthStore';
import { user } from './CurrentUser'
import { editor } from './EditorStore'

const store = {
    authStore,
    user,
    editor
};

window.store = store;

export { store };

然后将该商店导入他们需要的地方。

现在我有一些问题:

  1. 如果我需要从authStore收到userStore.user,如何在userStore构造函数中设置我的currentUser.uid? Ive tried to import **authStore** to **userStore** and versa, but it didnt帮助,因为两个观察者(authStatusChange和userRef.on('value')必须放在商店构造函数中(我是对的吗?)。因为​​我在开始时创建了一个storeClass实例 - 他们在auth.currentUser得到肯定响应之前实例化从服务器。我通过在两个商店中插入authStatusChange观察器来解决这个问题,但我认为这不是好的解决方案
  2. 在我的应用程序中,只有当userStore.user存在时,才能显示某些组件,如果我不使用@observable - 我可以通过if(user)…检查,但因为他的可观察量if(user)返回true - 因为他返回了可观察对象。我如何检查用户是否已经设置了?
  3. db中的用户有field-project。 Project是深度嵌套的对象,我用它来描述用户项目结构并在前面显示。当用户进入编辑器时 - 编辑器组件将此项目拆分为块。每个块都有自己的样式属性,用户可以编辑。因此,当用户选择某个块时,通过使用@action setCurrentBlock将此块作为currentBlock可观察对象在editorStore中写入,并作为参数接收对所选块的引用。 class EditorStore {@observable currentBlock = null; constructor () { } @computed get blockStyles () { return this.currentBlock.style } @action setCurrentBlock ( block ) { this.currentBlock = block } @action updateBlockStyle ( data ) { const { styleProp, value } = data; this.currentBlock.style[ styleProp ] = value; } } const editor = new EditorStore(); export {editor};

所以我的editStylesPanel组件显示来自@computed blockStyles的当前块样式值。一切都很好,但是当我通过@action updateBlockStyle更改一些样式属性时 - 他只更新editorStore.currentBlock的样式,并且不会更改user.project的相关块中的样式。我确信如果我发送对该对象的引用 - 那么必须在根对象上发生t editorStore的任何更改。为什么这不会发生?

  1. 最后一个问题 - 将商店注入组件的更好方法是什么?通过qazxsw poi和qazxsw poi或者qazxsw poi

谢谢你的帮助;)

javascript reactjs firebase mobx mobx-react
1个回答
1
投票

这是我在同样情况下所做的事情:

<Provider store={…stores}>

虽然它有效,但我希望有更好的解决方案。也许@inject(‘store’)

© www.soinside.com 2019 - 2024. All rights reserved.