首页 > 解决方案 > React 和 mobx :在商店中使用域类

问题描述

我尝试通过 react 和 typescript 学习 mobx 的用法。

我想做点什么,但我不知道这是否可行,以及这是否是一个好习惯。

我想要一个商店(在我的例子中是 GridStore)和一个域类(网格),比如服务/实体结构。

我尝试类似

export default class GridStore {
    private rootStore: RootStore;

    @observable grid: Grid;

    constructor(rootStore: RootStore) {
        this.rootStore = rootStore;
        this.grid = new Grid();
    }

    @action
    select = (x: number, y: number) => {
        // the grid.select change grid's properties which are used in component
        if (this.grid.select(x, y)) {
            // if change do some stuff
        }
    }
}

我没有任何结果。编辑:我的意思是组件不会重新渲染。在第一个示例中更精确一点,Grid 类不包含 mobx 注释,它只是一个带有 props 和方法的类。

所以我尝试像使用带有 mobx 注释的商店一样使用 Grid。它似乎有点作用。

// rootStore
export class RootStore {
    gridStore: GridStore;
    grid: Grid;
    constructor() {
        this.grid = new Grid();
        this.gridStore = new GridStore(this);
    }
}

// in GridStore
@action
select = (x: number, y: number) => {
    // the gird.select change grid's properties which are used in component
    if (this.rootStore.grid.select(x, y)) {
            // if change do some stuff
        }
    }
}

在我看来,Grid 类只是一个简单的类而不是商店。并且 GridStore 具有可观察的 Grid 属性。这是正确的推理吗?我可以使用像我的第一个示例这样的东西吗?如果是,如何?如果不是,什么是好的做法?

谢谢

标签: reactjstypescriptmobxmobx-react

解决方案


推荐阅读