今天我开始使用 MobX,遇到的第一个问题是如何在 Observable 更新时执行 React 类组件中的函数。
我的印象是可以使用
reaction
来实现这一点,但我不确定如何使其发挥作用。
class MissionLog {
private _missions: Array<IMissionItem> = [];
public get missions() {
return this._missions;
}
constructor() {
makeAutoObservable(this);
}
// Example of a method that modifies the _missions array
public receiveMission(mission: IMissionItem) {
this._missions.push(mission);
}
}
export const missionLog = new MissionLog();
// Example of modifying the missions array
missionLog.receiveMission(someMission);
export const ObserverTest = observer(class _ObserverTest extends React.Component {
constructor(props: any) {
super(props);
// Executes the console.log at the start,
// but not when missionLog.missions changes.
autorun(() => {
console.log("Autorun", missionLog.missions);
})
// Never executes the console.log
reaction(
() => missionLog.missions,
(mission) => {
console.log("Reaction");
}
)
}
render() {
return (
// Accessing missionLog.missions here
// gives me the correct, updated data,
// so my setup should be fine.
)
}
});
我也尝试过用
intercept
和observe
来代替reaction
,但也没有结果。
看起来我们都遇到了同样的问题,而且 Mobx 的文档很差劲:-D。
如果我错了,请纠正我,但根据他们的文档,react() 的作用就像 React 中的 useEffect 函数。
您基本上应该将其放置在应用程序中需要反应的任何地方。