我正在创建一个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
,则App
在currentX
更改时不再重新呈现。为什么会这样?我已经在currentX
中使用App
作为道具值,那么它是否应该自动重新渲染?
2)每当我按下鼠标并调用onPointPress
时,它就会成功将patternInProgress
更新为true
。由于patternInProgress
是observable
并且在组件App
的呈现方法中使用,App
会在patternInProgress
更改为true
时重新呈现在onPointPress
方法内。这也导致PatternLine
组件的重新渲染(这是期望的)。
然而,问题是传递给PatternLine
的道具没有被更新(而是传递null
)。即drawLine
方法未成功更新商店内的lastNode
,currentX
和currentY
。
我无法弄清楚为什么会这样。我在这做错了什么?
请注意,我没有显示调用drwaLine
方法的组件的代码。但是,我已经测试过调用组件正确地将currentX
和currentY
传递给drwaLine
。
答案 0 :(得分:0)
您的代码有拼写错误。当你应该说 PatternLine 时,你正在导入 PatterLine 。