去除 mobx-react 和 props

Debounce mobx-react and props

我正在尝试去抖方法调用:"chart.calculateChartData(props.answers)"。

我试过: - 自动运行 - 反应 - 使用反应库中的去抖动。 - 在 calculateChartData

中设置超时

每个解决方案都导致更新周期或不起作用,因为 MobX 不是不可变的。

有人提示吗?

function QuantificationChart(props: QuantificationChartProps) {
    const {t} = useTranslation();

    const rootStore = useRootStore();
    const chart = rootStore.formulaStore.getChart<Chart>(Chart.chartName);
    const data = chart.calculateChartData(props.answers);
calculateChartData = (questionData: { [id: string]: number; } = {}) => {
        let chartData = [];
        for (let i = 0; i < this.numberOfYears + 1; ++i) {
            let customData = {...questionData, "year" : i};
            let chartEntry = {
                cost: this.rootStore.formulaStore.calculateFormula(this.cost.formula, customData),
                earn: this.rootStore.formulaStore.calculateFormula(this.earn.formula, customData),
                sum: 0
            };
            chartEntry.sum = (chartEntry.earn - chartEntry.cost) + (chartData[i - 1]?.sum || 0);
            chartData.push(chartEntry);
        }
        return chartData;
    };

提示:这是我使用 MobX 的第一个项目

找到解决办法。似乎有效:

基于:https://mobx-react.js.org/recipes-effects

    const [data, setData] = React.useState(chart.calculateChartData(props.answers));

    React.useEffect(
        () =>
            autorun(() => {
                setData(chart.calculateChartData(props.answers));
            }, {delay: 1000}),
        [],
    );