0
私はちょっとした蛇のゲームを書こうとしており、ヘビの方向を変えることにトラブルを抱えています。私は下のコンポーネント全体を含んでいます。 this.setState is not a function
this.setStateは関数ではありませんsetInterval react
この
が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>
)
}
}
はい、ああ、完全な意味があります!ありがとう!実際には、クラスにバインドされている 'changeDirection'である必要がありますので、答えを更新する必要があります。 –
@peterflanagan私は、各ハンドラをバインドする代わりに' class'に自動バインドするarrow関数を使用する方が簡潔ですバインドするハンドラがたくさんあるときは面倒になり、余分な束をコードに追加します) –