mobx - 使 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()
)来强制重新渲染。但这感觉就像一个黑客。有没有更好的办法?
解决方案
回答我自己的问题......
我查看了几个选项,但所有选项都很笨拙。我最终决定重新设计 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>) {
...
}
推荐阅读
- python - 如何获得具有连续日期时间行的扩展数据框?
- r - How to calculate a ratio for each month in a year and attach 12 ratio columns (will be 12 columns) to the origianl dataset in R?
- python-3.x - 在 Matplotlib 的 X 轴上间隔日期
- node.js - 猫鼬只更新选定的字段
- spring-boot - 如何使用 MockMvc 为您的 REST 控制器创建单元测试
- reactjs - 将钩子或函数传递给子组件
- wordpress - EC2 无法连接到 mySQL RDS
- java - 我想使用父目录的父目录
- javascript - 用于什么“../..”?我今天在这一行找到了它 var express = require('../..');
- java - 在后端 Angular 10 + Spring Boot 中未正确接收授权标头