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>
)
}
}
啊,是的,完全合理!谢谢!它实际上应该是绑定到类的'changeDirection',所以你应该更新答案 –
@peterflanagan我发现使用自动绑定到'class'的箭头函数更简洁,而不是绑定每个处理程序(有时当你得到一堆处理程序来绑定它时会变得乏味,并为你的代码添加更多的行) –