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 나는 각 클래스를 바인딩하는 대신에 클래스에 자동 바인드하는 arrow 함수를 사용하는 것이 더 간결하다는 것을 알았습니다. 바인딩 할 핸들러가 많아지면 지루해지며 코드에 여러 줄을 추가합니다. –