MobX - 类组件内的反应

问题描述 投票:0回答:1

今天我开始使用 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
,但也没有结果。

reactjs mobx mobx-react
1个回答
0
投票

看起来我们都遇到了同样的问题,而且 Mobx 的文档很差劲:-D。

如果我错了,请纠正我,但根据他们的文档,react() 的作用就像 React 中的 useEffect 函数。

您基本上应该将其放置在应用程序中需要反应的任何地方。

© www.soinside.com 2019 - 2024. All rights reserved.