Mobx / React体系结构问题。基本上,我只想将简单的可重用模型对象传递给修改它们的简单可重用组件。这些模型对象可能是更复杂的数据结构的属性。进行更改后,我需要调用相应的API。
我看过许多示例,可以想到许多不同的方法来实现此目的,但是我不确定最好的方法是什么。
假设我有一个简单的可重用类,其中包含一些可观察的属性。
class Widget {
@observable name: string;
@observable weight: number;
@action setName(val: string) { this.name = val; }
@action setWeight(val: number) { this.weight = val; }
}
现在,假设此小部件在其他类中多次使用。例如:
class RobotWithWidget {
@observable widget: Widget;
@observable power: number;
}
class CarWithWidgets {
@observable widgets: Array<Widget>;
}
想象一下,与在CarWithWidgets中更改小部件相比,更改RobotWithWidget中的小部件时,应调用不同的API。
接下来我有我的商店:
class MainStore {
@observable robot: RobotWithWidget;
@observable car: CarWithWidgets;
}
第一个问题:Widget,RobotWithWidget和CarWithWidgets是否被视为域对象?
无论如何,现在我有了我的React组件来编辑小部件属性。
@observer
class WidgetEditor extends React.Component<Widget> {
我真的只想传递一个Widget并让组件对其进行操作。但是,当更改名称或权重时,我需要在某个地方调用适当的API来更新正在编辑的对象。 同样,根据小部件的来源,API也会有所不同。
以下是我考虑过的一些选项:
WidgetEditor
不仅接受widget
,而且接受interface Actions { setName(name:string)
之类的东西。这可以在商店本身上实现。该组件将调用提供的操作以对窗口小部件进行更改(而不是直接修改窗口小部件)。因此,在这种情况下,WidgetEditor
将接受IWidget,而我们会传递RobotWidgetStore
,依此类推。
interface IWidget {
name: string;
weight: number;
setName(val: string);
setWeight(val: number);
}
class RobotWidgetStore implements IWidget {
@computed get name() { return mainStore.robot.widget.name; }
@action setName(val: string) {
mainStore.robot.widget.setName(val);
// call /put/robot API to update
@computed get weight() { return mainStore.robot.widget.weight; }
@action setWeight(val: number) {
mainStore.robot.widget.weight(val);
// call /put/robot API to update
}