Mobx组件不会在可观察值的变化上重新呈现

时间:2018-05-28 11:46:00

标签: javascript reactjs mobx mobx-react

我正在创建一个React应用程序并使用Mobx进行状态管理。这是我的代码:

商店:

import { observable, action } from 'mobx';

class UnlockApp {

    @observable unlockPoints = 9;
    @observable pattern = null;
    @observable patternInProgress = false;
    @observable lastPoint = null;
    @observable allNodes = null;
    @observable lastNode = null;
    @observable currentX = null;
    @observable currentY = null;
    @observable isPatternLineEmpty = true;

    @action onPointPress = (point) => {
        this.pattern = [];
        this.pattern.push(point);
        this.patternInProgress = true;
        this.lastPoint = point;
        this.isPatternLineEmpty = false;
    }

    @action drawLine = (currentX, currentY) => {
        if (this.patternInProgress) {
            this.lastNode = this.allNodes[this.lastPoint].current;
            this.currentX = currentX;
            this.currentY = currentY;
        }
    }

    @action handleMouseEnter = (point) => {
        if (this.patternInProgress) {
            this.pattern.push(point);
            this.lastPoint = point;
            this.isPatternLineEmpty = false;
        }
    }

    @action stopCounting = () => {
        this.patternInProgress = false;
        this.lastPoint = null;
    }

    @action updateNodes = (nodes) => {
        this.allNodes = nodes;
    }

}

export default new UnlockApp();

组件:

import React from 'react';
import ReactDOM from 'react-dom';
import { observer } from 'mobx-react';
import PatternLine from './components/pattern-line/pattern-line';
import PatternScreen from './components/pattern-screen/pattern-screen';
import UnlockApp from './store';

const App = observer(() => {
    console.log(UnlockApp.currentX);
    return (
        <div>
            <PatternScreen store={UnlockApp} />
            {
                UnlockApp.patternInProgress &&
                <PatternLine lastNode={UnlockApp.lastNode}
                    currentX={UnlockApp.currentX}
                    currentY={UnlockApp.currentY} />
            }
        </div>
    )
})

有两个问题:

1)如果我从console.log(UnlockApp.currentX)组件中移除App,则AppcurrentX更改时不再重新呈现。为什么会这样?我已经在currentX中使用App作为道具值,那么它是否应该自动重新渲染?

2)每当我按下鼠标并调用onPointPress时,它就会成功将patternInProgress更新为true。由于patternInProgressobservable并且在组件App的呈现方法中使用,App会在patternInProgress更改为true时重新呈现在onPointPress方法内。这也导致PatternLine组件的重新渲染(这是期望的)。

然而,问题是传递给PatternLine的道具没有被更新(而是传递null)。即drawLine方法未成功更新商店内的lastNodecurrentXcurrentY

我无法弄清楚为什么会这样。我在这做错了什么? 请注意,我没有显示调用drwaLine方法的组件的代码。但是,我已经测试过调用组件正确地将currentXcurrentY传递给drwaLine

1 个答案:

答案 0 :(得分:0)

您的代码有拼写错误。当你应该说 PatternLine 时,你正在导入 PatterLine