我正在尝试编写一个小蛇游戏,并且在改变蛇的方向时会遇到麻烦。我在下面列出了整个组件。
我看到以下错误:
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>
)
}
}
答案 0 :(得分:3)
这不是类函数的绑定,你必须在构造函数中手动完成,
试试这个:
constructor(props){
super(props);
this.state = {
snakeLeftPos: 0,
snakeDirection: 'right',
boardWidth: 20,
boardHeight: 20
};
this.moveSnake = this.moveSnake.bind(this);
}