使 React 展示组件对 MobX 存储更改做出反应的任何方式
Any way to make a React presentational component react to MobX store changes
我有一个 React table 组件,它通过一个名为 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。我希望 table 组件在基于 MobX 的商店发生变化时重新渲染:
<MaterialTable tableStore={orderStore} />
然而这并没有发生,因为 table 组件不是 MobX 观察者。有没有办法强制 table 组件重新渲染?例如,我可以通过取消引用父组件中的商店来强制重新渲染(使用简单的 console.log()
)。但这感觉像是一个 hack。有没有更好的方法?
回答我自己的问题....
我看了几个选项,但都不太好。我最终决定重新设计 table 组件的 props 以传入数组而不是抽象的 TableStore
接口(table 组件无法对其作出反应)。这让我可以避免将 MobX 作为依赖项添加到 table 组件库,同时仍然在父组件中利用 MobX。总之,父组件现在监视 MobX 存储,通过创建新数组并将其传递给 table 组件来对更改做出反应。
这是 table 组件的新界面:
export interface MaterialTableProps<T extends Entity> extends TableProps {
entityList: Array<T>;
}
export function MaterialTable<T extends Entity>(props: MaterialTableProps<T>) {
...
}
我有一个 React table 组件,它通过一个名为 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。我希望 table 组件在基于 MobX 的商店发生变化时重新渲染:
<MaterialTable tableStore={orderStore} />
然而这并没有发生,因为 table 组件不是 MobX 观察者。有没有办法强制 table 组件重新渲染?例如,我可以通过取消引用父组件中的商店来强制重新渲染(使用简单的 console.log()
)。但这感觉像是一个 hack。有没有更好的方法?
回答我自己的问题....
我看了几个选项,但都不太好。我最终决定重新设计 table 组件的 props 以传入数组而不是抽象的 TableStore
接口(table 组件无法对其作出反应)。这让我可以避免将 MobX 作为依赖项添加到 table 组件库,同时仍然在父组件中利用 MobX。总之,父组件现在监视 MobX 存储,通过创建新数组并将其传递给 table 组件来对更改做出反应。
这是 table 组件的新界面:
export interface MaterialTableProps<T extends Entity> extends TableProps {
entityList: Array<T>;
}
export function MaterialTable<T extends Entity>(props: MaterialTableProps<T>) {
...
}