2017-10-20 83 views
0

我想寫一個小蛇遊戲,並有麻煩改變方向的蛇。我已經在下面包含了整個組件。this.setState不是一個函數setInterval react

我看到下面的錯誤:

this.setState is not a function

這被在changeDirection方法造成的。

請參見下面全碼:

export default class Example extends Component { 

constructor(props){ 
    super(props); 
    this.state = { 
     snakeLeftPos: 0, 
     snakeDirection: 'right', 
     boardWidth: 20, 
     boardHeight: 20 
    }; 
    } 

componentDidMount() { 
    document.onkeydown = this.changeDirection; 
    setInterval(() => { 
     this.moveSnake(); 
    }, 1000); 
} 

moveSnake() { 
    const { boardWidth, snakeDirection} = this.state; 

    if(snakeDirection === 'right') { 
     this.setState((prevState) => { 
     return snakeDirection: prevState.snakeDirection + 20 
     }); 
    } 

    //same logic for other directions 
    } 

    changeDirection(e) { 
    switch(e.keyCode) { 
     case 37: 
     this.setState(() => { 
     return { 
      snakeDirection: 'left' 
     } 
     }); 
     break; 

     //other switch cases omitted for right, up, down 
    } 
    } 

    render() { 

    const { snakeLeftPos, boardHeight, boardWidth } = this.state; 
    return(
     <div> 
     <Snake snakeLeftPos={snakeLeftPos} /> 
     <Board boardHeight={boardHeight} boardWidth={boardWidth}/> 
     </div> 
    ) 
    } 

} 

回答

3

這是不是證券類的功能,你所要做的是在構造函數中,

試試這個:

constructor(props){ 
    super(props); 
    this.state = { 
     snakeLeftPos: 0, 
     snakeDirection: 'right', 
     boardWidth: 20, 
     boardHeight: 20 
    }; 
    this.moveSnake = this.moveSnake.bind(this); 
    } 
+0

啊,是的,完全合理!謝謝!它實際上應該是綁定到類的'changeDirection',所以你應該更新答案 –

+0

@peterflanagan我發現使用自動綁定到'class'的箭頭函數更簡潔,而不是綁定每個處理程序(有時當你得到一堆處理程序來綁定它時會變得乏味,併爲你的代碼添加更多的行) –

相關問題