【发布时间】:2018-05-28 11:45:59
【问题描述】:
我正在创建一个 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) 如果我从App 组件中删除console.log(UnlockApp.currentX),App 在currentX 更改时不再重新渲染。为什么会这样?我已经在App 中使用currentX 作为道具值,所以它不应该自动重新渲染吗?
2) 每当我按下鼠标并调用onPointPress 时,它都会成功地将patternInProgress 更新为true。由于patternInProgress 是一个observable 并在组件App 的渲染方法中使用,当patternInProgress 在onPointPress 方法中更改为true 时,App 会重新渲染。这也会导致PatternLine 组件的重新渲染(这是需要的)。
但是,问题在于传递给PatternLine 的道具没有被更新(而是传递了null)。即drawLine 方法没有成功更新商店内的lastNode、currentX 和currentY。
我不明白为什么会这样。我在这里做错了什么?
请注意,我没有显示调用drwaLine 方法的组件的代码。但是,我已经测试过调用组件正确地将currentX 和currentY 传递给drwaLine。
【问题讨论】:
标签: javascript reactjs mobx mobx-react