ES6 React类变量意外行为

时间:2019-03-05 12:27:10

标签: javascript reactjs ecmascript-6

我正在使用React 16.7,ES6类变量也无法按照我认为的方式处理。

我正在构造函数中创建一个对象this.currentStroke

export class CanvasLineDrawer extends React.Component {
constructor(props) {
    super(props);
    this.currentStroke = {
        start: [],
        points: []
    }; 
    this.state = {
        canvas: null,
        context: null,
        mousePressed: false,
        strokes: []
    };
    this.canvasRef = React.createRef();
    this.handleMouseDown = this.handleMouseDown.bind(this);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.handleMouseUp = this.handleMouseUp.bind(this);
}

我使用此字段在与HTML画布上绘制的线有关的数据上打孔。

我还创建了一个辅助方法,将该字段重置为其初始空白状态,以便我可以存储在画布上绘制的下一行的内容。

    resetCurrentStroke() {
    this.currentStroke['start'] = [];
    this.currentStroke['points'] = [];
}

在我的应用程序过程中,我向this.currentStroke对象添加了一些内容,然后在绘制完线条后将这些值推入我的反应状态,然后调用resetCurrentStroke函数。

    handleMouseUp() {
    this.setState({
        mousePressed: false,
        strokes: [...this.state.strokes, this.currentStroke]
    }, function() {
        console.log(this.state.strokes);
        this.resetCurrentStroke();
    });
}

问题在于,即使我在setState的回调中具有resetCurrentStroke函数,也似乎在将变量添加到状态之前对其进行了重置。在上面的当前实现中,console.log返回一个空对象,但是如果我删除this.resetCurrentStroke()调用,它将表现良好。

谢谢

0 个答案:

没有答案