首页 > 解决方案 > 使 React 展示组件对 MobX 存储更改做出反应的任何方式

问题描述

我有一个 React 表组件,它通过一个名为TableStore. 这个道具是获取行数据的高级抽象:

interface TableStore<RowType> {
    getRowIds: () => Array<RowId>;
    getRow: (rowId: RowId) => RowType | undefined;
}

interface MaterialTableProps<RowType> {
    tableStore: TableStore<RowType>;
}

function MaterialTable<RowType>(props: MaterialTableProps<RowType>) {
    ...
}

如您所见MaterialTable,它不是 MobX 观察者。它是不依赖于 MobX 的组件库的一部分。

当我在我的应用程序中使用这个组件时,我为它提供了一个基于 MobX 的 TableStore。每当基于 MobX 的存储发生更改时,我希望表组件重新呈现:

<MaterialTable tableStore={orderStore} />

然而,这不会发生,因为 table 组件不是 MobX 观察者。有没有办法强制表格组件重新渲染?例如,我可以通过取消引用父组件中的存储(使用简单的console.log())来强制重新渲染。但这感觉就像一个黑客。有没有更好的办法?

标签: mobxmobx-react

解决方案


回答我自己的问题......

我查看了几个选项,但所有选项都很笨拙。我最终决定重新设计 table 组件的 props 以传入数组而不是抽象TableStore接口(table 组件无法响应)。这使我能够避免将 MobX 作为依赖项添加到表组件库中,同时仍然在父组件中利用 MobX。总之,父组件现在监视 MobX 存储,通过创建一个新数组并将其传递给表组件来对更改做出反应。

这是表格组件的新界面:

export interface MaterialTableProps<T extends Entity> extends TableProps {
    entityList: Array<T>;
}

export function MaterialTable<T extends Entity>(props: MaterialTableProps<T>) {
    ...
}

推荐阅读