首页 > 解决方案 > 按钮单击时无法读取 null 的属性“setState”

问题描述

我正在开发一个 reactjs 应用程序,并且在访问 updateVert 函数中的状态时遇到了这个问题。当我单击“播放”按钮时,会调用 actionButton 并从 actionButton 内部调用 updateVert。

下面是我的代码片段

updateVert() {

        console.log("inside upver")
        if(play) {
            cancelAnimationFrame(this.updateVert);
            return;
        }

       this.setState({xPos: this.state.xPos + 1}, ()=>{
           if(this.state.xPos >= w) {
               // stop animation...
               this.setState({xPos:0, playing:false});
           }
           ctx.clearRect(0, 0, w, h);

           // draw new one...
           ctx.beginPath();
           ctx.strokeStyle = "#19f";
           ctx.lineWidth = 2;
           ctx.moveTo(this.state.xPos, 0);
           ctx.lineTo(this.state.xPos, 200);
           ctx.stroke();

           if(this.state.playing) {
               console.log("yes true")
               requestAnimationFrame(this.updateVert)
           };
       })
        // reset rectangle content to erase previous line...
    }

    actionButton(){
        if(this.state.playing) {
            // pause...
            this.setState({playing:false},()=>{
                console.log(this.state.playing)
            })
        }
        else {
            this.setState({playing:!this.state.playing},()=>{
                console.log(this.state.playing)
                this.updateVert();
            })

        }
    }

  render() {
        return (
            <div>
                <div className="App">
                    <canvas id="DemoCanvas" width="500" height="200"></canvas>
                </div>
                <button onClick={this.actionButton.bind(this)}>{this.state.playing ? "Stop":"Play"}</button>
            </div>


    );
  }

当我单击按钮(播放/暂停)时,我收到错误消息

TypeError: Cannot read property 'setState' of null
updateVert
src/App.js:45
  42 |      return;
  43 |  }
  44 | 
> 45 | this.setState({xPos: this.state.xPos + 1}, ()=>{
  46 |     if(this.state.xPos >= w) {
  47 |         // stop animation...
  48 |         this.setState({xPos:0, playing:false}); 

我已经正确引用了 updateVert 函数。我究竟做错了什么?

标签: javascriptreactjs

解决方案


您缺少绑定上下文this

actionButton(){您调用的钩子this.updateVert()中,没有绑定this. 因此将其绑定在构造函数中:

this.updateVert.bind(this)

推荐阅读